简体   繁体   中英

Python restructuring dictionary

I have the following dict in Python

{1500: 2, 1400: 1, 700: 10}

and I have a hard time turning it into the following:

[{"x": 1500, "y": 2}, {"x": 1400, "y": 1}, {"x": 700, "y": 10}]

How do I do this? Is there some list comprehension for it?

Yes there is.

[{"x": k, "y": v} for k, v in my_dict.items()]
myDict = {1500: 2, 1400: 1, 700: 10}

[{'x': key, 'y': myDict[key]} for key in myDict]

you can also use a simple for loop:

data = {1500: 2, 1400: 1, 700: 10}
result = []

for x, y in data.items():
    result.append({"x": x, "y": y})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM