简体   繁体   English

将元组的元组转换为具有键值对的字典

[英]Convert tuple of tuples to a dictionary with key value pair

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}]

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. 然后只需使用zip来创建单独的词典。

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}]

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}]

using lambda function 使用lambda函数

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}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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