Linux

# Python Dictionary Tips

So far you have learned Python, In this page you will learn Python Dictionary tips and tricks.

## Convert a Sequence to Python dictionary

So far, you have seen how to convert a sequence into a list and tuple. Now you'll see how to convert a sequence to Python Dictionary. By using function dict(), you can convert a sequence into a Dictionary. Let us explore this.
>>> list1 = ['a','b']
>>> dict[list1]
Traceback (most recent call last):
ValueError: dictionary update sequence element #0 has length 1; 2 is required

It would give error, because dict() function need special kind of sequence.

>>> list1 = [(1, 'a'), (3, 'c'), (2, 'b'), (4, 'd')]
>>> dict(list1)
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}

Give tuple to dict() function.
>>> tuple1 = ((1, 'a'), (3, 'c'), (2, 'b'), (4, 'd'))
>>> dict(tuple1)
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
Now, you can see a how sequence convert in to a Python Dictionary.
Let us discuss another example.
>>> list1 = [(1, 'a'), (3, 'c'), (2, 'b'), (2, 'd')]
>>> dict(list1)
{1: 'a', 2: 'd', 3: 'c'}
The Python list use repeated values. The dict() function takes latest value as key.

## Inverting a Python dictionary

In this section we will study different methods to invert a Python dictionary.

### Inverting a Python Dictionary using zip()

Let us see, how to zip() to invert a Python dictionary.
>>> dict1 = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
>>> dict1.values()
['a', 'b', 'c', 'd']
>>> dict1.keys()
[1, 2, 3, 4]
>>> dict2 = zip(dict1.values(), dict1.keys())
>>> dict2
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> dict(dict2)
{'a': 1, 'c': 3, 'b': 2, 'd': 4}

Now, you can see, how zip() and dict() functions invert a Python dictionary.

### Inverting a Python Dictionary using Dictionary comprehension

Let us see a simple example of Dictionary comprehension to invert the Python dictionary.

>>> dict1 = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
>>> {value: key for key, value in dict1.items()}
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
See below diagram to understand the working. Inverting a Python Dictionary

## Making Python Dictionary from two Python lists

Up to this level of Python you can make Python dictionary from two list, but now you have to do it with in one line logic.
>>> list1 = [1,2,3,4]
>>> list2 = ['a','b','c','d']
>>> dict(zip(list1,list2))
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
From above logic you can see, one line logic to create Python dictionary from two lists. There is another method to perform same operation. Here we will use map() and lambda functions.
>>> list1 = [1,2,3,4]
>>> list2 = ['a','b','c','d']
>>> dict(map(lambda k,v: (k,v), list1, list2))
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
Here Lambda is a function, list1 and list2 are the arguments. map() function produce a sequence, eligible for dict() function.