Sometimes, we want to group Python dictionary keys as a list and create a new dictionary with this list as a value.
In this article, we’ll look at how to group Python dictionary keys as a list and create a new dictionary with this list as a value.
How to group Python dictionary keys as a list and create a new dictionary with this list as a value?
To group Python dictionary keys as a list and create a new dictionary with this list as a value, we can loop through the dict items and call setdefault
to set the default value for each key.
For instance, we write
v = {}
for key, value in sorted(d.items()):
v.setdefault(value, []).append(key)
to create a new empty dict v
.
Then we use a for loop to loop through the key-value pairs in dict d
returned by d.items
.
In the loop, we call v.setdefult
to add a new entry with key value
and value key
.
Conclusion
To group Python dictionary keys as a list and create a new dictionary with this list as a value, we can loop through the dict items and call setdefault
to set the default value for each key.