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.
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
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}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With