A dictionary in Python is a collection of unordered data items. Where each item consists of a key-value pair. Python dictionaries are similar to associative arrays in PHP.
Creating a Python Dictionary
A Python dictionary is created by placing all the key-value pairs(key: value) inside curly braces {}, provided that each key-value pair is separated by a comma. A key must be of an immutable(unchangeable) type. However, values can be of any valid or user-defined type and can also be repetitive. A key must be unique within one dictionary.
Note: Keys are unique within one dictionary.
# A program to create a dictionary in Python # Empty dictionary empty_dict = {} print(empty_dict) # Dictionary with integral keys int_dict = {1:'Programmers', 2:'Portal'} print(int_dict) # Dictionary with string keys str_dict = {'name': 'John', 'age':23} print(str_dict) # Mixed dictionary mixed_dict = {1:'hello', 'fruits':['Apple', 'Orange'], 'tpl':(1, 2, 'Hii') } print(mixed_dict)
Output:
{} {1: 'Programmers', 2: 'Portal'} {'name': 'John', 'age': 23} {1: 'hello', 'fruits': ['Apple', 'Orange'], 'tpl': (1, 2, 'Hii')}
Creating a Dictionary using built-in method
Python also provides us with an inbuilt method dict() to create a dictionary. It is basically a constructor, which takes a sequence of key: value pairs as a parameter to create a dictionary.
Note: Passing a parameter to dict() method is optional.
# A program to create a Python dictionary using inbuilt method dict() # Empty dictionary empty_dict = dict() print(empty_dict) # Passing an object to create a dictionary sample_dict = dict({'name':'John','age':23}) print(sample_dict) # Passing a list of key-value pairs my_dict = dict([('name', 'John'),('age', 23)]) print(my_dict)
Output:
{} {'name': 'John', 'age': 23} {'name': 'John', 'age': 23}
Accessing Items of a Python Dictionary
As we already know, a python dictionary is unordered. Therefore, it does not support indexing. Dictionaries use the concept of keys to access their items. A dictionary use key inside a square bracket [] to access its value.
# A program to access items of a Python dictionary sample_dict = { 'name':'Programmers Portal', 'topic': 'Python', 'subTopic': 'Python Dictionaries' } print(sample_dict['name']) print(sample_dict['topic']) print(sample_dict['subTopic']) # Try to get the value of a key which does not exist print(sample_dict['unknown']) # It will through a key error
Output:
Programmers Portal Python Python Dictionaries Traceback (most recent call last): File "jdoodle.py", line 13, in <module> print(sample_dict['unknown']) KeyError: 'unknown'
Accessing Items using get() Method
In the last example, we observed that if we try to access the value of a key that does not exist, Python throws an error. So, what if we want to display the value of the key if it exists, if not it should display None. That’s exactly what the get() method does.
# A program to demonstrate get() method in a Python dictionary sample_dict = { 'name':'Programmers Portal', 'topic': 'Python dictionary', } print(sample_dict.get('name')) # Displays value of the key 'name' print(sample_dict.get('unknown')) # Displays None
Output:
Programmers Portal None
Adding and updating Dictionary Items
Python dictionaries are mutable. We can add new items to it. An assignment operator (=) is used to add new items to a dictionary.
# A program to add and update dictionary items sample_dict = { 'name': 'John' } print('Dictionary before: ', sample_dict) # Add age and gender to sample_dict sample_dict['age'] = 23 sample_dict['gender'] = 'Male' print('After adding age and gender: ', sample_dict) # Update existing items sample_dict['name'] = 'John Doe' # Replace John with John Doe sample_dict['age'] = 32 print('Dictionary after updating name and age: ', sample_dict)
Output:
Dictionary before: {'name': 'John'} After adding age and gender: {'name': 'John', 'age': 23, 'gender': 'Male'} Dictionary after updating name and age: {'name': 'John Doe', 'age': 32, 'gender': 'Male'}
Remove/delete items from a dictionary
As we already discussed, dictionaries are mutable objects. We can remove/delete any item from the dictionary. There are mainly four methods that are used to remove items from a dictionary. These methods are listed below:
- Using pop() method
- Using del keyword
- Using popitem() method
- Using clear method
1. Using pop() method
This method accepts a parameter, which is the key of the item to be removed. It returns the value of the removed item.
# A program to demonstrate pop() method in Python dictionary sample_dict = { 'name':'Programmers Portal', 'topic': 'Python', 'subTopic': 'Python list' } print('List before: ',sample_dict) val = sample_dict.pop('subTopic') print('After removing topic: ', sample_dict) print('Removed item: ',val) # Displays 'Python list'
Output:
List before: {'name': 'Programmers Portal', 'topic': 'Python', 'subTopic': 'Python list'} After removing topic: {'name': 'Programmers Portal', 'topic': 'Python'} Removed item: Python list
2. Using del keyword
Python provides us a built-in keyword del which can be used to delete a single item or to delete the whole dictionary itself. The key to be removed is passed inside square brackets [].
# A program to demonstrate del keyword in a Python dictionary sample_dict = { 'name': 'John', 'age': 23, 'roll': 81, 'site': 'Programmers Portal' } print('Initial dictionary: ', sample_dict) del sample_dict['roll'] # Removes 'roll' from dictionary print('After removing roll: ', sample_dict) del sample_dict # Deletes the whole dictionary permanently print('After deleting dictionary: ', sample_dict) # Above line will throw an error as the dictionary doesn't exists
Output:
Initial dictionary: {'name': 'John', 'age': 23, 'roll': 81, 'site': 'Programmers Portal'} After removing roll: {'name': 'John', 'age': 23, 'site': 'Programmers Portal'} Traceback (most recent call last): File "jdoodle.py", line 14, in <module> print('After deleting dictionary: ', sample_dict) NameError: name 'sample_dict' is not defined
3. Using popitem() method
The popitem() method removes a random item from the dictionary. It returns the removed item as a tuple of key and value.
# A program to demonstrate popitem() method in a Python dictionary sample_dict = { 'name':'apple', 'taste':'sweet', 'rotten':False } print('Initial Dictionary: ', sample_dict) val = sample_dict.popitem() print('After removal: ', sample_dict) print('Removed item: ',val)
Output:
Initial Dictionary: {'name': 'apple', 'taste': 'sweet', 'rotten': False} After removal: {'name': 'apple', 'taste': 'sweet'} Removed item: ('rotten', False)
4. Using clear() method
The clear() method removes all the items from a dictionary. However, it does not delete it permanently.
# A program to demonstrate the clear() method in Python dictionary sample_dict = { 'key':'name', 'value':'John' } print('Initial dictionary: ', sample_dict) # Remove all items sample_dict.clear() print('After clearing all items: ', sample_dict)
Output:
Initial dictionary: {'key': 'name', 'value': 'John'} After clearing all items: {}
Loop Through a Dictionary
Python for loop can be used to access each key and value of a dictionary. Different methods can be used to get keys and values.
1. Print All Keys:
When we apply a simple for loop on a dictionary, it returns all the keys.
Example:
# A program to loop through a dictionary my_dict = { 'name': 'John', 'age':23, 'gender':'Male' } for key in my_dict: print(key)
Output:
name age gender
2. Print All Values:
# A program to print all values in a dictionary my_dict = { 'name': 'John', 'age':23, 'gender':'Male' } for key in my_dict: print(my_dict[key])
Output:
John 23 Male
3. Using values() method to Print All Values:
We can use the inbuilt method values() to print each value in a dictionary.
Example:
# A program to print all values in a dictionary using values() method my_dict = { 'name': 'John', 'age':23, 'gender':'Male' } for value in my_dict.values(): print(value)
Output:
John 23 Male
4. Print All Keys and Values Using items() method:
The items() method returns each key-value pair.
Example:
# A program to print all key-value pairs in a dictionary my_dict = { 'name': 'John', 'age':23, 'gender':'Male' } for key,value in my_dict.items(): print(key,value)
Output:
name John age 23 gender Male
Check if a Key Exists in the Dictionary
To check if a key exists in the dictionary or not, we can use the in keyword.
It returns True if the specified key exists in the dictionary, otherwise it returns False.
Example:
# A program to check if a key exists in the dictionary my_dict = { 'name': 'John', 'age':23, 'gender':'Male' } if 'age' in my_dict: print('Exists') print('age', my_dict['age'])
Output:
Exists age 23