A case of dictionary inversion in Python

  • 2021-08-12 03:13:07
  • OfStack

Sometimes you encounter the need to reverse the dictionary, that is, the key in the dictionary is the value, and the value in the dictionary is the key. For dictionaries that are small, you can use the common method

Method 1:

Convert using common methods


>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> def invert_dict(d):
...   return dict([(v,k) for (k,v) in d.iteritems()])
...
>>> invert_dict(d)
{1: 'a', 2: 'b', 3: 'c'}

Method 2:

Use the izip method in the itertools module to transform


>>> d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> from itertools import izip
>>> def invert_dict(d):
...   return dict(izip(d.itervalues(), d.iterkeys()))
...
>>> invert_dict(d)
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
>>>

Remarks:

1. When the dictionary is large, it is much more efficient to use izip method in itertools module.

2. The value before inversion should ensure that it is not a list, which cannot be hash, otherwise it cannot be inversion.

Additional knowledge: python dictionary key and value flip output code

I won't talk too much, let's just look at the code ~


dict=eval(input()) # Input format: dict = {"a":1,"b":2}
dict_new={}
try:
  for k,v in dict.items():
    dict_new[v]=k
  print(dict_new)
except:
  print(" Input error ")

Related articles: