Linux

Python List & Dictionary advance Operation

Up to this level you are well versed with Dictionaries and lists. In this page you will see the mix operation of list and dictionary. In this page we will discuss different scenario for mix operation of list and dictionary.

Python List with in list

Consider a scenario where you have to insert list with in the list.

Example

Consider a example of Python list with in the list.
list1 = ['a', 'b', 'c', ['h', 'i', 't'], ['k','u']]

How to create this type of Python dictionary

Here we will use append() method. Let us see the example below.
Python list with list
Python list with list
Now you can see how append() method insert the list with in the list.

Accessing the Python list

accessing Python list with list
Accessing Python list with list
You can see how to access list within list by using subscript operator.

Python Dictionary with in Dictionary

Let us discuss the example.
Python dictionary with dictionary
Python dictionary with dictionary
You can see the Python dictionary with dictionary.
Now see the accessing Python dictionary with in dictionary
Accessing Python dictionary with dictionary
Accessing Python dictionary with dictionary
The dict1['e'] represents the internal dictionary. The dict1['e']['c'] represents the corresponding item of key 'e' in internal dictionary.

Python Dictionary with list

Example

Consider you want to store multiple items in one key of dictionary. In simple words one key of dictionary can hold multiple items.
In this case we have to use dictionary with list. The key of dictionary will hold one list. as shown below.
Python dictionary with list
Python Dictionary with lists
Let write a program to handle this situation.
Python Dictionary with list
Python Dictionary with list
Click to view code
You can see the from code, make a list and assign list as item of dictionary.

Python List with Dictionary

In this section we will how you can store dictionary in list. It is very simple make dictionary and use as item of list. As shown below.
list1 = [ {'a':1}, {'b':2},{'c':3} ]
Access the Python List with Dictionary.
Python list with dictionary
Python Dictionary with list
I hope you know to how it works. The list1[0] represents the first item of list means first dictionary. The list1[0]['a'] represents the first item of key "a" of first dictionary. The list1[0]['c'] give error because key "c" does not belong to first dictionary.
Consider a another example.
list1 = [ {'a':1}, {'a':2} , {'a':3} ]
same key with different values.
Consider a simple program for this.
Python Dictionary with list
Python list with dictionary
Click to view code
There is no error but output is not same as we expect. Last dictionary is copied in the place of all list items. In order to remove this programming error we will use dict.copy() method. let us discuss with new code.
dict.copy()
Python list with dictionary
Click to view code
This time we got desire output.





admin