So I have a dictionary which looks like the following:
dictionary={('a','b'):1,('c','d'):2}
As you can see there are multiple keys for a value. What I would like to do is basically drop (delete) one of the keys. For example, I want to say that all values will not need the first key anymore and convert the above dictionary to the following:
dictionary={'b':1,'d':2}
What would be the safest way of doing this?
Thanks
您可以使用字典理解在每个元组中删除第一项:
dictionary = {k: v for (_, k), v in dictionary.items()}
I don't like assuming the structure of keys. To make it absolutely bomb-proof
from collections import Iterable
d = {
k[-1] if isinstance(k, Iterable) else k: v
for k, v in dictionary.iteritems()
}
In case you have keys that are not lists or tuples, you will want to use this:
d ={('a','b'):1,('c','d'):2}
new_d = {a[-1] if isinstance(a, tuple) or isinstance(a, list) else a:b for a, b in d.items()}
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.