Python Dictionary
Python Dictionary
A Python dictionary is a mutable collection of unordered key- values pair data. It stores key along with its value, so that a key can access its respective value.
A Python dictionary stores dictionary items that can be retrieved very fast by their key.
The keys must be unique within a dictionary. The dictionary’s value can be of any type, but the keys must be of an immutable data type such as numbers, strings, or tuples.
Creating a dictionary
A Python dictionary stores data in key-value pair within the curly bracket {}, where key and value are separated by a colon (:). For example:
student={'name':'Himanshu','age':11,'class':'Fifth','Roll_no':17}
print(type(student))
print(student)
Output:
{'name': 'Himanshu', 'age': 11, 'class': 'Fifth',’Roll_no’:17} An empty dictionary is declared by empty curly {} braces. student={} print(type(student))
Output:
Dictionary operations
Accessing value from the dictionary
We can access the value from a dictionary by using the index operator [], and the key is used inside the square brackets. Python also provides the get() method to access the value. For example.
student={'name':'Himanshu','age':11,'class':'Fifth','Roll_no':17} #accessing element using with key print(student['name']) print(student['age']) print(student['Roll_no']) #accessing value using with get() print(student.get('class'))
Output:
Himanshu 11 17 Fifth
- If we try to access a value that does not exist in the given dictionary then we get an error.
student = {'name':'Himanshu','age':11,'class':'Fifth','Roll_no':17} print(student['subject'])
Output:
line 2, in <module> print(student['subject']) KeyError: 'subject'
- If we use the get() method for non-existing value. It will not show an error but return None. For example:
student = {'name':'Himanshu','age':11,'class':'Fifth','Roll_no':17} print(student.get('subject'))
Output:
None
Modification (update) in Dictionary
We can update a dictionary by adding new key-value pair. The dictionary is mutable data type so its value can be updated or deleted by using specific keys. For example:
student = {'Name':'Himanshu','Age':11,'Class':'Fifth','Roll_no':17} student['School']='Dps School' #Adding New key with its value student['Age'] = 12 #update existing value print(student)
Output:
{'Name': 'Himanshu', 'Age': 12, 'Class': 'Fifth', 'Roll_no': 17, 'School': 'Dps School'}
Deletion in Dictionary
The element of the dictionary can be deleted by using the del keyword. We can either remove the single element or clear entire dictionary.
student = {'Name':'Himanshu','Age':11,'Class':'Fifth','Roll_no':17} del student['Class'] #deleting the Class key print(student) print(student['Class'])
Output:
line 9, in <module> {'Name': 'Himanshu', 'Age': 11, 'Roll_no': 17} print(student['Class']) KeyError: 'Class'
Python provides the clear() method to clear all element of dictionary. It returns an empty dictionary.
student = {'Name':'Himanshu','Age':11,'Class':'Fifth','Roll_no':17} student.clear() #deleting all the element of the dictionary print("The empty string is:",student)
Output:
The empty string is: {}
Properties of Dictionary Keys
There are few points to remember about dictionary keys.
- In the dictionary, the duplicate key is not allowed, which means we cannot define the same key for multiple values. If we declare the same key for multiple values, then, it will store the last assigned value. Consider the following example.
student = {'Name':'Himanshu','Age':11,'Class':'Fifth','Roll_no':17,'Name':'Dev'} # We assign Name key with multiple time then it will consider the last assigned value print("Last assign name is:",student['Name'])
Output:
Last assign name is: Dev
- The dictionary keys must be immutable, which means we can use numbers, strings or tuple as a key. But mutable like [‘key’] is not allowed. For example:
student = {['Name']:'Himanshu','Age':11,'Class':'Fifth'} print(student)
Output:
line 2, in <module> student = {['Name']:'Himanshu','Age':11,'Class':'Fifth'} TypeError: unhashable type: 'list'
Built-in Dictionary functions
The built-in functions and their descriptions are given below:
Sr. no. | Functions | Description |
1. | len(dict) | It is used to compute the length of dictionary |
2. | cmp(dict1, dict2) | It compares the elements of both the dictionary. |
3. | str(dict) | It converts the dictionary into printable string representation. |
4. | type(variable) | It is used to print the type of the passed variable. |