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