簡體   English   中英

將元組的元組轉換為具有鍵值對的字典

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

我有以下元組元組:

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

我怎么能把它變成這樣的字典列表

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

使用列表理解如下。 首先創建一個鍵列表,它將重復所有元組。 然后只需使用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}]

您可以使用列表理解:

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

這使:

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

使用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)

產量

[ {"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