Python Programming – Python Dictionary

In the previous sections, we learned sequence data types such as Python lists, tuples, and sets. Herein, in this section, we learn Python dictionary. Python dictionary is a compound data type, which contains a pair comprising of a key-value corresponding to the value of an element. Or in other words, every data element of a dictionary is associated with a key value. The data element of a dictionary can be retrieved or accessed through its key value.

Creating a Dictionary

The Python dictionary is a collection of unordered pairs of key values and their associated data elements. Dictionary contains heterogeneous kind of data, where key must be unique and of an immutable type. In Python, a dictionary can be created as shown in Code 5.38. In this program, Python dictionary is created in four ways. The elements of a dictionary must be enclosed in curly braces {}. Initially data_dictl is created containing two keys ‘Name’ and ‘Rollnp’ with corresponding values. Then, a dictionary data_dict2 is created, which contains list as one its elements. Subsequently, data_dict3 is created using a Python built-in method dict( ), which encloses the values of dictionary keys and their values. At last, data_dict4 is created using diet(’) method, where keys and associated values are assigned as pairs. The output of all 4 created dictionaries is given for more understanding.

Code: 5.3 8.Illustration of creating a Dictionary.

#illustration of creating a dictionary in Python

data_dictl={‘Name’: ‘Robin’, ‘Rollno’: 111}
print(datadictl)

data_dict2= {‘Name’: ‘Robin’, ‘Rollno’: 111, ‘Marks’: [45, 67,74]}
print(data_dict2)

data_dict3=dict({rName’: ‘Sam’, ‘Rollno’: 222})
print(data_dict3)
1
data dict4=dict([(‘Name’, ‘Karl’), (‘Rollno’, 333)])
print(data dict4)

Output

{‘Name’: ‘Robin’, ‘Rollno’: 111}
{‘Name’: ‘Robin’, ‘Marks’: [45, 67, 74], ‘Rollno’: 111}
{‘Name’: ‘Sam’, ‘Rollno’: 222}
{‘Name1: ‘Karl’, ‘Rollno’: 333}

Accessing a Dictionary

In the previous section, we learn how to create a dictionary in Python. We have also accessed the complete dictionary by printing the dictionary name using the Python built-in print() function. The method to access element values of a dictionary based on their key values is expressed in this section. The elements of a dictionary can be accessed in a very simple way. The programming illustration for the same is given in Code 5.39. In this program, we see that two dictionaries are created and their complete form is accessed using the print ( ) function.

However, the values of keys ‘Name’ and ‘Rollno’ are accessed using the square bracket [] referring to the key term of the dictionary. In the program, the value of ‘Name’ and ‘Rollno’ are accessed using their respective keys, the Python language also provides a built-in method get() for fetching the value of a particular key of a dictionary. The output for the same can be seen in the output section of the given code.

Code: 5.39. Illustration of accessing a dictionary.

#illustration of Accessing a Python Dictionary

data_dictl={Name’: ‘Robin’, ‘Rollno’: 111}
print(data_dictl)

data_dict2= {‘Name’: ‘Robin’, ‘Rollno’: 111, ‘Marks’:[45, 67, 74]}
print(data_dict2)

print(data_dictl [‘Name’])
print(data_dictl [‘Rollno’])

print(data_dict2.get(Name’))
print(data_dict2.get(‘Rollno’))
print(data_dict2.get(‘Marks’))

Output

{‘Rollno’: 111, “Name’: ‘Robin’}
{‘Marks’: [45, 67, 74], ‘Rollno’: 111, Name’: ‘Robin’}
Robin
111
Robin
111
[45, 67, 74]

Updating a Dictionary

The Python programmer can. easily add or modify the elements of a dictionary. If the item is already present in the dictionary, then its value can be altered by providing a new value to its key term. If the item does not exist in the dictionary, then a new key and its value can be added to the dictionary. Code 5.40 illustrates this concept. In the program, we see that a dictionary data_dict is created with two keys values ‘Name’ and ‘Rollno’ with their values ‘Robin’ and ill respectively. Now, we modify the value of key ‘Rollno’ to 222 and then add a new key-value ‘Marks’ with its values as marks of three subjects provided as a list. Now, while printing the data_dict, we see that the updated values are displayed in the output. Thus, we see that it is very simple to add or modify the elements of a Python dictionary.

Code: 5.40. Illustration of updating a Python dictionary.

#illustration of updating a Python Dictionary

data_dict={rName’: ‘Robin’, ‘Rollno’: 111}
print(data_dict)

data_dict[‘Rollno’]=222
data_dict[‘Marks’]=[34,28,45]

print(data_dict)

Output

{Name’: ‘Robin’, ‘Rollno’: 111}
{‘Name’: ‘Robin’, ‘Rollno’: 222, ‘Marks’: [34,28,45]}

Removing or Deleting Elements of a Dictionary

The Python language provides two methods pop() and clear}) to remove elements of a dictionary. The pop() method is used to remove the dictionary element with the specified key value. Another method popitem}) can also be used to remove an element from the Python dictionary arbitrarily.

The clear}) the method is used to remove all the elements of a Python dictionary. Another method del is used to delete a specific element or entire dictionary. The programming illustration for the same is given in Code 5.41. In this program, we see that a dictionary is created with four keys ‘Name’. ‘Rollno’, ‘Marks’ and ‘Mobile’ with their corresponding values. Initially, pop}) the method is used to remove ‘Rollno’ from the dictionary. Then, popitem}) is used to remove arbitrarily an element from the dictionary. In this program, the ‘Name’ key with its value is removed. Next, the del method is used to remove the ‘Mobile’ key and value. In the end, the list is emptied by the clear method. The complete concept can be better understood by referring to the output of the program.

Code: 5.41, Illustration of removing or deleting dictionary elements.

#illustration of removing or deleting a Dictionary elements

data_dict={‘Name’: ‘Robin’, ‘Rollno’: 111, Marks’:[40, 50, 60], ‘Mobile’:
9764377641}
print(data_dict)

print(data_dict.pop(‘Rollno’))
print(data_dict)

print(data_dict.popitem())

del data_dict[‘Mobile’]
print(data_dict)

print(data dict.clear())

Output
{‘Rollno’: 111, ‘Name’: ‘Robin’, ‘Marks’: [40, 50, 60], ‘Mobile’: 9764377641}
111
{“Name’: ‘Robin’, Marks’: [40, 50, 60], ‘Mobile’: 9764377641}
(‘Name’, ‘Robin’)
{‘Marks’: [40, 50, 60]}
None

Python Dictionary Methods

The Python language provides various methods to be used with dictionaries. The list of dictionary methods is given in Table 5.10.

Method Description
pop(key) Removes an element from the dictionary whose key is given as its argument
popitem() Removes an arbitrary element from the dictionary and returns its value
clear() Removes all the elements of the dictionary
eopy() Creates a shallow copy of the dictionary
items() Returns a new view of dictionary items
keys() Returns a new view of dictionary keys
update([other]) Updates the dictionary with the specified key and value
get(key) Returns the value of key

Python Dictionary Membership Test

As studied earlier, the membership of a particular item in a list, tuple or set is determined by using the ‘in’ operator. Similarly, ‘in’ operator is used with the Python dictionary also to determine the presence of a particular key in the dictionary. It is to be noted here that the ‘in’ operator is applicable over dictionary keys and not on the values. It is demonstrated in Code 5.42. This program shows the use of ‘in’ operator. As the key ‘Name’ is present in the dictionary, therefore, the result of ‘Name’ in data dict comes out to be True. Nevertheless, the values ‘Robin’ is tested by using the ‘in’ operator, which results in False, although ‘Robin’ is the member of data_dict. As mentioned earlier, the ‘in’ operator is applicable on keys only and not on values.

Code 5.42. Illustration of membership operator ‘in’.

#illustration of membership test of dictionary key

data_dict= {Name’: ‘Robin’, ‘Rollno’: 111, ‘Marks’:[40, 50, 60]}

printCName’ in data_dict)
print(‘Robin’ in data diet)

Output
True
False

Alike, list and tuple, the Python dictionaries are iterable. The elements of the Python dictionary can be accessed through for loop as shown in Code: 5.43. It can be seen from the program that the individual element values of the dictionary are accessed using for loop. If the programmer uses the statement print(i) only inside the for loop, then dictionary keys will be iterated.

Code: 5.43. Illustration of dictionary iteration using for loop.

#illustration of using for loop with dictionary

data_dict={‘Name’: ‘Robin’, ‘Rollno’: 111, ‘Marks’:[40, 50, 60]}

for i in data_dict:
print(data_dict[i])

Output
Robin
111
[40, 50, 60]

Python Dictionary Functions

The Python language provides built-in functions to be used with a dictionary. The list is tabulated in Table 5.11.

Function

Description

Sorted( ) Sorts the elements of the dictionary
len() Returns the length of the dictionary
cmp() Compares items of two dictionaries
any() Returns true if any of the dictionary items is true
all() Returns true if all the items of the dictionary are true

Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *