Transpose values and key in a dictionary when values are not unique
dictionary, mapping, python, reverse
Solution
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]}
Problem
I want to change keys to values in a python dictionary, but the values in the original dictionary are not unique. Here is what I have: ``` 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} ``` When I tried to convert it using a for loop, I only got one matching pair for each person.