Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}]
like image 823
iznogoddd Avatar asked May 25 '19 22:05

iznogoddd


3 Answers

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}]
like image 102
Sheldore Avatar answered Sep 24 '22 19:09

Sheldore


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}]
like image 45
Cleb Avatar answered Sep 24 '22 19:09

Cleb


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}]
like image 23
sahasrara62 Avatar answered Sep 23 '22 19:09

sahasrara62