How do you best swap the key:value pair of a dictionary?

Recommended Answers

All 4 Replies

In case of the capital:state pair I did it this way:

def swap_dictionary(original_dict):
    temp_dict = {}
    dict_list = original_dict.items()
    for i in dict_list:
        temp_dict[i[1]] = i[0]
    return temp_dict

cs = {"indianapolis":"indiana", "columbus":"ohio", "jackson":"mississippi",
      "phoenix":"arizona", "honolulu":"hawaii", "richmond":"virginia",
      "springfield":"illnois", "lincoln":"nebraska",
      "boston":"massachuettes", "lansing":"michigan", "desmoines": "iowa",
      "salem": "oregon"}

dic = swap_dictionary(cs)
print dic

"""
{'mississippi': 'jackson', 'arizona': 'phoenix', 'iowa': 'desmoines', 
'massachuettes': 'boston', 'michigan': 'lansing', 'virginia': 'richmond', 
'oregon': 'salem', 'hawaii': 'honolulu', 'nebraska': 'lincoln', 
'indiana': 'indianapolis', 'ohio': 'columbus', 'illnois': 'springfield'}
"""

If you like to practice with list comprehension, you can use this ...

def swap_dictionary(original_dict):
    return dict([(v, k) for (k, v) in original_dict.iteritems()])

Thank you,
what would happen to a swap if I had a dictionary with duplicate values like this:

d = {'a': 1, 'b': 1, 'c':1, 'd':99}
>what would happen to a swap if I had a dictionary with duplicate values like this:
>        d = {'a': 1, 'b': 1, 'c':1, 'd':99}

You would get something like {1: 'b', 3: 'x'}, so you would loose some info. To avoid this, you could do the following:

In [7]: def swap(d):
   ...:     new = {}
   ...:     for key, value in d.items():
   ...:         if value in new.keys():
   ...:             new[value].append(key)
   ...:         else:
   ...:             new[value] = [key]
   ...:     return new
   ...: 

In [8]: d
Out[8]: {'a': 1, 'x': 3, 'c': 1, 'b': 1}

In [9]: swap(d)
Out[9]: {1: ['a', 'c', 'b'], 3: ['x']}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.