当值不唯一时,转置值并在python字典中键入键 [英] Transpose values and key in python dictionary when values are not unique
本文介绍了当值不唯一时,转置值并在python字典中键入键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将键更改为python字典中的值,但是原始字典中的值不是唯一的.
I want to change keys to values in a python dictionary, but the values in the original dictionary are not unique.
这就是我所拥有的:
year_person = {2000: ‘Linda’, 2001: ‘Ron’, 2002: ‘Bruce’, 2003: ‘Linda’, 2004: ‘Bruce’, 2005 ‘Gary’, 2006: ‘Linda’}
这就是我想要将其更改为:
This is what I want to change it to:
person_year = {‘Linda’: 2000, ‘Ron’: 2001, ‘Bruce’: 2002, ‘Linda’, 2003: ‘Bruce’, 2004 ‘Gary’, 2005: ‘Linda’: 2006}
当我尝试使用for循环将其转换时,每个人只有一对匹配对.
When I tried to convert it using a for loop, I only got one matching pair for each person.
推荐答案
您也可以使用defaultdict来做到这一点:
You can also do it with a defaultdict:
year_person = {2000: 'Linda', 2001: 'Ron', 2002: 'Bruce', 2003: 'Linda', 2004: 'Bruce', 2005: 'Gary', 2006: 'Linda'}
from collections import defaultdict
d = defaultdict(list)
for k, v in year_person.items():
d[v].append(k)
print dict(d)
>>> {'Bruce': [2002, 2004], 'Linda': [2000, 2003, 2006], 'Ron': [2001], 'Gary': [2005]}
这篇关于当值不唯一时,转置值并在python字典中键入键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文