Python: Replace All Values in a Dictionary
Sure, you can do something like:
d = {x: 1 for x in d}
That creates a new dictionary d
that maps every key in d
(the old one) to 1
.
You can use a dict comprehension (as others have said) to create a new dictionary with the same keys as the old dictionary, or, if you need to do the whole thing in place:
for k in d:
d[k] = 1
If you're really fond of 1-liners, you can do it in place using update
:
d.update( (k,1) for k in d )