问题
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