Switching keys and values on a Python dictionary

This is a stupid question I asked in the office today: Imagine you have dictionary and you want to build a new dictionary where the keys are the values and the values are the keys.

Gak came with

new_dict = dict(zip(old_dict.values(), old_dict.keys()))

Thinking about it, I came with

new_dict = dict([(old_dict[k], k) for k in old_dict.keys()])

I know that keys will not return a list anymore on Python 3, so I guess my solution is the right one. :)

2 thoughts on “Switching keys and values on a Python dictionary

  1. dict() takes an iterator so you can use a “iterator” comprehension, or whatever they’re called instead!

    dict(((old_dict[k], k) for k in old_dict.keys()))

    But in the case of passing an iter-comprehension literal you don’t have to use an extra set of parens

    dict((old_dict[k], k) for k in old_dict.keys())

    and then to make it more pretty use items(), or for mo effieciency use iteritems (tho deprecated in p3000):

    dict( (v, k) for k, v in old_dict.items() )


Comments are closed.