Convert tuple of tuples to a dictionary with key value pair

眉间皱痕 提交于 2021-02-16 08:39:11

问题


I have the following tuple of tuples:

tuples=((32, 'Network architectures', 5), (33, 'Network protocols', 5))

How could I turn it into a list of dictionary like this

dict=[ {"id": 32, "name": "Network architectures", "parent_id": 5}, {"id": 33, "name": "Network protocols", "parent_id": 5}]

回答1:


Using a list comprehension as follows. First create a list of keys which will repeat for all the tuples. Then just use zip to create individual dictionaries.

tuples=((32, 'Network architectures', 5), (33, 'Network protocols', 5))

keys = ["id", "name", "parent_id"]

answer = [{k: v for k, v in zip(keys, tup)} for tup in tuples]
# [{'id': 32, 'name': 'Network architectures', 'parent_id': 5},
#  {'id': 33, 'name': 'Network protocols', 'parent_id': 5}]



回答2:


You can use a list comprehension:

[{'id': t[0], 'name': t[1], 'parent_id': t[2]} for t in tuples]

which gives:

[{'id': 32, 'name': 'Network architectures', 'parent_id': 5},
 {'id': 33, 'name': 'Network protocols', 'parent_id': 5}]



回答3:


using lambda function

tuples=((32, 'Network architectures', 5), (33, 'Network protocols', 5))
dicts = list(map(lambda x:{'id':x[0],'name':x[1], 'parent_id':x[2]}, tuples))
print(dicts)

output

[ {"id": 32, "name": "Network architectures", "parent_id": 5}, {"id": 33, "name": "Network protocols", "parent_id": 5}]


来源:https://stackoverflow.com/questions/56309228/convert-tuple-of-tuples-to-a-dictionary-with-key-value-pair

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!