Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a list of dictionaries from a list of keys and a list of values

How to create a dictionary of dictionaries from existing lists of keys and values?

celebr = ['Tony','Harry','Katty','Sam']
perc = [69,31,0,0]

d = dict(zip(celebr, perc))
dlist = []
for i in d.items():
    dlist.append(i)    
print(dlist)

Output:

[('Tony': 69), ('Harry': 31), ('Katty': 0), ('Sam': 0)]

When I use d.items it automatically gives me tuples, not dictionaries. Is there a way of creating a list of dictionaries, not tuples?

I need to get the following structure:

[{'Tony': 69}, {'Harry': 31}, {'Katty': 0}, {'Sam': 0}]
like image 766
Ivan Shelonik Avatar asked Aug 07 '17 08:08

Ivan Shelonik


4 Answers

Good use case for list comprehension:

dlist = [{k: v} for k, v in zip(celebr, perc)]

Output:

>>> celebr = ['Tony', 'Harry', 'Katty', 'Sam']
>>> perc = [69, 31, 0, 0]
>>>
>>> [{k: v} for k, v in zip(celebr, perc)]
[{'Tony': 69}, {'Harry': 31}, {'Katty': 0}, {'Sam': 0}]
like image 149
ettanany Avatar answered Nov 15 '22 06:11

ettanany


Would this be enough

celebr = ['Tony','Harry','Katty','Sam']
perc = [69,31,0,0]

dlist = []

for i, j in zip(celebr, perc):
    dlist.append({i: j})

print dlist
like image 23
Naren Murali Avatar answered Nov 15 '22 06:11

Naren Murali


You can implement with zip and dict.

dict(zip(celebr,perc))

Results:

In [14]: celebr = ['Tony', 'Harry', 'Katty', 'Sam'] 
In [15]: perc = [69, 31, 0, 0]

In [16]: dict(zip(celebr,perc))
Out[16]: {'Harry': 31, 'Katty': 0, 'Sam': 0, 'Tony': 69}
like image 22
Rahul K P Avatar answered Nov 15 '22 05:11

Rahul K P


Your example merely creates a list containing the dicts items. Your question asks for a list of sets. If you really want individual dicts then use a colon to separate the key and the value:

>>> [{k, v} for (k, v) in d.items()]
[{'Tony', 69}, {'Harry', 31}, {'Katty', 0}, {'Sam', 0}]
>>> [{k: v} for (k, v) in d.items()]
[{'Tony': 69}, {'Harry': 31}, {'Katty': 0}, {'Sam': 0}]
like image 38
holdenweb Avatar answered Nov 15 '22 05:11

holdenweb