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

Viewed 8843

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}]
6 Answers

list comprehension seems to be the shortest and easiest way and also the python way to do this, but I think if someone find list comprehension difficult, they could first make a dictionary and then append to an empty list as follows:

keys = [1,2,3,4,5,6,7]
values = ['a','b','c','d','e','f','g']
counter = 0
lst = []
for key in keys:
    dct = {keys[counter]:values[counter]}
    lst.append(dct)
    counter += 1
print(lst)

output:

[{1: 'a'}, {2: 'b'}, {3: 'c'}, {4: 'd'}, {5: 'e'}, {6: 'f'}, {7: 'g'}]
Related