Home > Net >  Best way to process the update of dictionary in python
Best way to process the update of dictionary in python

Time:11-27

I wish to update my dictionary based on my values in a dictionary by looping it but my method is quite naive and not cool so I wish to seek help here to see whether is there better cool way with single line or maybe a few lines to process it to have the same output?

My code:

g_keypoints = {"test1": (14,145), "test2": (15, 151)}
d = {}
for k, v in g_keypoints.items():
    d.update({k "_x":v[0]})
    d.update({k "_y":v[1]})

My output:

{'test1_x': 14, 'test1_y': 145, 'test2_x': 15, 'test2_y': 151}

My expectation: single line or better pythonize way

CodePudding user response:

I think you basically want a solution using list comprehension.

g_keypoints = {"test1": (14,145), "test2": (15, 151)}
d = {}
[(d.update({k "_x":v[0]}), d.update({k "_y":v[1]})) for k,v in g_keypoints.items()]
print(d)

This seems to work and produces the same output you have, although I feel like the way you have it makes it is more readable than using a single line.

  • Related