Reputation: 468
Short question and probably short answer, but I do not get it^^
d = {'a' : 0, 'b' : 0, 'c' : 0, 'd' : 0}
l = [1, 2, 3, 4]
I want to set the list values to the dictionary such that
d = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}
Of course
d['a'], d['b'], d['c'], d['d'] = l
will make it, but that cant be the right way to do it. What if I have 50 values ... A loop that zips d
and l
will work as well.
But there is something short like d.values = l
, isn't it?
Thanks for helping! :)
Edit: I’m using Python 3.7, so the dict is ordered by insertion.
Upvotes: 0
Views: 13215
Reputation: 532448
No, there is no short-cut. You need to use dict.update
with a list of pairs.
d.update(zip(d, l))
Upvotes: 13
Reputation: 27515
In Python 3.7+ dicts are ordered in the order the items are inserted. Therefore the following would be correct.
d = {'a' : 0, 'b' : 0, 'c' : 0, 'd' : 0}
for i, k in enumerate(d.keys(), 1):
d[k] = i
Or you could use something like the following:
d['a'], d['b'], d['c'], d['d'] = range(1,5) #or 1, 2, 3, 4
Edit
One liner for you using a dict comprehension:
d = {key: val for val, key in enumerate(d.keys(), 1)}
Upvotes: 1