I have a dictionary which has predefined keys:
{1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None}
and a list with numeric values:
[0, 10, 20, 30, 40, 50, 60, 100]
I want to add these values from the list to the dictionary so that it will look like this:
{1: 0, 2: 10, 3: 20, 4: 30, 5: 40, 6: 50, 7: 60, 8: 100}
How can I add every item from the list to the next key of my dictionary?
You directly use zip
on the dict and the list of values, tha make pairs, then ues dict
to make mappings from pairs
d = {1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None}
v = [0, 10, 20, 30, 40, 50, 60, 100]
res = dict(zip(d, v))
print(res) # {1: 0, 2: 10, 3: 20, 4: 30, 5: 40, 6: 50, 7: 60, 8: 100}
You could find strange to passe the whole dict d
to zip
but iterating over th dict is same as iterating over its key in fact, the following can have more sense but it does the same
dict(zip(d.keys(), v))
Below is more dynamic solution where you dont have prepare half populated dict
a_list = [0, 10, 20, 30, 40, 50, 60, 100]
a_dict = {idx+1:val for idx,val in enumerate(a_list)}
print(a_dict)
output
{1: 0, 2: 10, 3: 20, 4: 30, 5: 40, 6: 50, 7: 60, 8: 100}
I have a dictionary which has predefined keys:
{1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None}
and a list with numeric values:
[0, 10, 20, 30, 40, 50, 60, 100]
I want to add these values from the list to the dictionary so that it will look like this:
{1: 0, 2: 10, 3: 20, 4: 30, 5: 40, 6: 50, 7: 60, 8: 100}
How can I add every item from the list to the next key of my dictionary?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.