In this article, we will discuss dictionaries in python and will try to answer questions like,
- What is a dictionary?
- Why do we need it?
- How to create a dictionary?
- How to access elements in a dictionary?
What is a dictionary in python?
In python, a dictionary is a kind of container that stores the items in key-value pairs, like,
This is an example of dictionary, which contain student names as keys and their age as values. Elements in the dictionary are stored as key-value pairs, where each value is mapped with a key. It is also known as associative array or hash table.
The above dictionary contains four items, i.e. four key-value pairs,
- Jack & 32
- Ritika & 31
- Mark & 22
- Mathew & 27
Why do we need dictionaries?
As a dictionary, keeps the elements in key-value mapping format and internally uses hashing for it; therefore, we can get a value from the dictionary by its key very quickly. In best cases, its complexity is O(1), whereas, in the worst case, its complexity can be O(n).
Frequently Asked:
- Python: Iterate over dictionary with index
- Add new key-value pair to Dictionary in Python
- Python : How to Remove multiple keys from Dictionary while Iterating ?
- Python: Loop / Iterate over all keys of Dictionary
If you want to know more about hashing check this article –>Â What is Hashing and Hash Table?
How to create a dictionary?
To create a dictionary, we can use curly braces, i.e., {}.
dictObj = {}
It will create an empty dictionary.
Now to create a dictionary with items, pass the key-value pairs in curly braces  {}. Also, in every couple, key & value will be separated by a colon (:).
Let’s understand by some examples,
Create a dictionary that contains student names as keys and their age as value i.e.
student_age = {'Jack': 32, 'Ritika': 31, 'Mark' : 22, 'Mathew' : 27}
This dictionary contains four items. We can print the dictionary to check it contents,
print(student_age)
Output:
{'Jack': 32, 'Ritika': 31, 'Mark': 22, 'Mathew': 27}
Essential points about keys in the dictionary
- Keys are always unique in the dictionary
- keys must be of an immutable data type, i.e., strings, numbers, or tuples.
- It means once a key-value pair is added in the dictionary then it cannot modify the key itself, although we can change the value associated with it.
For example, if we create a dictionary with duplicate keys and print its content,
student_age = {'Jack': 32, 'Ritika': 31, 'Jack' : 22} print(student_age)
Output:
{'Jack': 22, 'Ritika': 31}
The value of jack is overwritten because keys are always unique in a dictionary.
Important points about value in dictionaries.
The values in a dictionary can be of any type.
For example, let’s create a dictionary where key is integer and value is a list of strings i.e.
student_info = {11: ['varun', 'Delhi', 9911], 12: ['Jack', 'London', 2211], 13: ['Ritika', 'Mumbai', 3311]}
Similarly, a dictionary can have any object as the value.
How to access an item in the dictionary
Suppose we have a dictionary like this,
student_age = {'Jack': 32, 'Ritika': 31, 'Mark' : 22, 'Mathew' : 27}
We can access a specific item/pair in a dictionary using [] operator on the dictionary object. If we call the operator [] on the dictionary object and pass a key, then it will return its value is like this,
age = student_age ['Jack'] print('Age of Jack is : ', age)
Output:
Age of Jack is : 32
Now if we pass a key that doesn’t exist in the dictionary, then it returns a KeyError,
age = student_age ['abc']
Error
KeyError: 'abc'
So, we before accessing any value in a dictionary, we should first check if given keys exist in the dictionary or not i.e.
if 'abc' in student_age: age = student_age['abc']
Python Dictionary Tutorial - Series:
- What is a Dictionary in Python & why do we need it?
- Creating Dictionaries in Python
- Iterating over dictionaries
- Check if a key exists in dictionary
- Check if a value exists in dictionary
- Get all the keys in Dictionary
- Get all the Values in a Dictionary
- Remove a key from Dictionary
- Add key/value pairs in Dictionary
- Find keys by value in Dictionary
- Filter a dictionary by conditions
- Print dictionary line by line
- Convert a list to dictionary
- Sort a Dictionary by key
- Sort a dictionary by value in descending or ascending order
- Dictionary: Shallow vs Deep Copy
- Remove keys while Iterating
- Get all keys with maximum value
- Merge two or more dictionaries in python
Subscribe with us to join a list of 2000+ programmers and get latest tips & tutorials at your inbox through our weekly newsletter.
The complete example is as follows,
def main(): # Creating an empty dictionary dictObj = {} print('** Create dictionary of student names & their age ***') student_age = {'Jack': 32, 'Ritika': 31, 'Mark' : 22, 'Mathew' : 27} print(student_age) print('*** Dictionary with duplicate keys ***') student_age = {'Jack': 32, 'Ritika': 31, 'Jack' : 22} print(student_age) student_info = {11: ['varun', 'Delhi', 9911], 12: ['Jack', 'London', 2211], 13: ['Ritika', 'Mumbai', 3311]} print(student_info) print('*** Accessing items in a dictionary ***') student_age = {'Jack': 32, 'Ritika': 31, 'Mark': 22, 'Mathew': 27} # Access the value of item with key jack age = student_age['Jack'] print('Age of Jack is : ', age) # Passing a key in [] that don't exist, if 'abc' in student_age: age = student_age['abc'] if __name__ == '__main__': main()
Output:
** Create dictionary of student names & their age *** {'Jack': 32, 'Ritika': 31, 'Mark': 22, 'Mathew': 27} *** Dictionary with duplicate keys *** {'Jack': 22, 'Ritika': 31} {11: ['varun', 'Delhi', 9911], 12: ['Jack', 'London', 2211], 13: ['Ritika', 'Mumbai', 3311]} *** Accessing items in a dictionary *** Age of Jack is : 32