- Python Dictionary
- Create a Dictionary
- Python Dictionary Length
- Access Dictionary Items
- Change Dictionary Items
- Add Items to a Dictionary
- Remove Dictionary Items
- Python Dictionary Methods
- Dictionary Membership Test
- Iterating Through a Dictionary
- Table of Contents
- Python Dictionary – How to Perform CRUD Operations on dicts in Python
- How to create a dictionary in Python
- How to access dictionary values in Python
- How to update a dictionary in Python
- How to update a dict using the update() method
- How to remove elements from dictionary in Python
- How to remove elements from a dict with the pop() method
- How to remove an item from a dict with the popitem() method
- How to remove an item from a dict with the del keyword
- How to remove an item from a dict with the clear() method
- Dictionary Operators and Built-in Functions
- len() function
- sorted() function
- in operator
- Built-in Dictionary Methods
- How to iterate through a dictionary
- How to iterate through a dictionary using the items() method
- How to iterate through a dictionary using keys()
- How to iterate through a dictionary using values()
- How to merge dictionaries in Python
- Wrapping Up
Python Dictionary
In Python, a dictionary is a collection that allows us to store data in key-value pairs.
Create a Dictionary
We create dictionaries by placing key:value pairs inside curly brackets <> , separated by commas. For example,
# creating a dictionary country_capitals = < "United States": "Washington D.C.", "Italy": "Rome", "England": "London" ># printing the dictionary print(country_capitals)
The country_capitals dictionary has three elements (key-value pairs).
Note: Dictionary keys must be immutable, such as tuples, strings, integers, etc. We cannot use mutable (changeable) objects such as lists as keys.
# Valid dictionary my_dict = < 1: "Hello", (1, 2): "Hello Hi", 3: [1, 2, 3] >print(my_dict) # Invalid dictionary # Error: using a list as a key is not allowed my_dict = < 1: "Hello", [1, 2]: "Hello Hi", >print(my_dict)
Tip: We can also use Python’s dict() function to create dictionaries.
Python Dictionary Length
We can get the size of a dictionary by using the len() function.
country_capitals = < "United States": "Washington D.C.", "Italy": "Rome", "England": "London" ># get dictionary's length print(len(country_capitals)) # 3
Access Dictionary Items
We can access the value of a dictionary item by placing the key inside square brackets.
country_capitals = < "United States": "Washington D.C.", "Italy": "Rome", "England": "London" >print(country_capitals["United States"]) # Washington D.C. print(country_capitals["England"]) # London
Note: We can also use the get() method to access dictionary items.
Change Dictionary Items
Python dictionaries are mutable (changeable). We can change the value of a dictionary element by referring to its key. For example,
country_capitals = < "United States": "New York", "Italy": "Naples", "England": "London" ># change the value of "Italy" key to "Rome" country_capitals["Italy"] = "Rome" print(country_capitals)
Add Items to a Dictionary
We can add an item to the dictionary by assigning a value to a new key (that does not exist in the dictionary). For example,
country_capitals = < "United States": "New York", "Italy": "Naples" ># add an item with "Germany" as key and "Berlin" as its value country_capitals["Germany"] = "Berlin" print(country_capitals)
Note: We can also use the update method() to add or change dictionary items.
Remove Dictionary Items
We use the del statement to remove an element from the dictionary. For example,
country_capitals = < "United States": "New York", "Italy": "Naples" ># delete item having "United States" key del country_capitals["United States"] print(country_capitals)
Note: We can also use the pop method() to remove an item from the dictionary.
If we need to remove all items from the dictionary at once, we can use the clear() method.
country_capitals = < "United States": "New York", "Italy": "Naples" >country_capitals.clear() print(country_capitals) # <>
Python Dictionary Methods
Here are some of the commonly used dictionary methods.
Function | Description |
---|---|
pop() | Remove the item with the specified key. |
update() | Add or change dictionary items. |
clear() | Remove all the items from the dictionary. |
keys() | Returns all the dictionary’s keys. |
values() | Returns all the dictionary’s values. |
get() | Returns the value of the specified key. |
popitem() | Returns the last inserted key and value as a tuple. |
copy() | Returns a copy of the dictionary. |
Dictionary Membership Test
We can check whether a key exists in a dictionary using the in operator.
my_list = print(1 in my_list) # True # the not in operator checks whether key doesn't exist print("Howdy" not in my_list) # False print("Hello" in my_list) # False
Note: The in operator checks whether a key exists; it doesn’t check whether a value exists or not.
Iterating Through a Dictionary
A dictionary is an ordered collection of items (starting from Python 3.7). Meaning a dictionary maintains the order of its items.
We can iterate through dictionary keys one by one using a for loop.
country_capitals = < "United States": "New York", "Italy": "Naples" ># print dictionary keys one by one for country in country_capitals: print(country) print("----------") # print dictionary values one by one for country in country_capitals: capital = country_capitals[country] print(capital)
Table of Contents
Python Dictionary – How to Perform CRUD Operations on dicts in Python
Ashutosh Krishna
One of the most important composite data types in Python is the dictionary. It’s a collection you use to store data in pairs.
Dictionaries are ordered and mutable, and they cannot store duplicate data. Just keep in mind that before Python 3.6, dictionaries were unordered.
Alright, let’s dive in and learn more about how they work.
How to create a dictionary in Python
As we know, a dictionary consists of a collection of pairs. A colon ( : ) separates each key from its associated value.
We can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ( <> ).
In the above example, Name , Roll , and Subjects are the keys of the dictionary my_dict . Ashutosh Krishna , 23 , and [«OS», «CN», «DBMS»] are their respective values.
We can also declare a dictionary using the built-in dict() function like this:
A list of tuples works well for this:
my_dict = dict([ ("Name", "Ashutosh Krishna"), ("Roll", 23), ("Subjects", ["OS", "CN", "DBMS"]) ])
They can also be specified as keyword arguments.
my_dict = dict( Name="Ashutosh Krishna", Roll=23, Subjects=["OS", "CN", "DBMS"] )
How to access dictionary values in Python
You can’t access dictionary values using the index.
If you try to do this, it will throw a KeyError like this:
Traceback (most recent call last): File "C:\Users\ashut\Desktop\Test\hello\test.py", line 7, in print(my_dict[1]) KeyError: 1
Notice that the exception is called KeyError. Does that mean the dictionary values can be accessed using the keys? Yes, you got it right!
You can get a value from a dictionary by specifying its corresponding key in square brackets ( [] ).
>>> my_dict['Name'] 'Ashutosh Krishna' >>> my_dict['Subjects'] ['OS', 'CN', 'DBMS']
If a key doesn’t exist in the dictionary, we get a KeyError exception as we saw above.
>>> my_dict['College'] Traceback (most recent call last): File "", line 1, in KeyError: 'College'
But we can also avoid this error using the get() function.
If the key exists in the dictionary, it will retrieve the corresponding value. But if it doesn’t exist, it won’t throw an error.
How to update a dictionary in Python
Dictionaries are mutable, which means they can be modified. We can add a new pair or modify existing ones.
Adding a new item in the dictionary is quite easy using the assignment operator, like this:
>>> my_dict['College'] = 'NSEC' >>> my_dict
If the key is already present in the dictionary, it will update the value of that key.
How to update a dict using the update() method
We can also update the dictionary using the built-in update() method like this:
>>> my_dict >>> another_dict = >>> my_dict.update(another_dict) >>> my_dict >>>
The update() method takes either a dictionary or an iterable object of key/value pairs (generally tuples).
>>> my_dict.update(Branch='CSE') >>> my_dict
How to remove elements from dictionary in Python
There are several ways to remove elements from a Python dictionary.
How to remove elements from a dict with the pop() method
We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the provided key and returns the value .
>>> roll = my_dict.pop('Roll') >>> roll 35 >>> my_dict
How to remove an item from a dict with the popitem() method
The popitem() removes the last key-value pair and returns it as a tuple:
>>> my_dict.popitem() ('Branch', 'CSE') >>> my_dict
How to remove an item from a dict with the del keyword
You can use the del keyword to delete a particular pair or even the entire dictionary.
>>> del my_dict['Subjects'] >>> my_dict >>> del my_dict >>> my_dict Traceback (most recent call last): File "", line 1, in NameError: name 'my_dict' is not defined
How to remove an item from a dict with the clear() method
The clear method clears all the pairs in the dictionary.
>>> my_dict >>> my_dict.clear() >>> my_dict <>
Notice that after the clear() method is called, printing the dictionary doesn’t throw an error because the clear() method doesn’t remove the dictionary. But the del keyword removes the dictionary too. That’s why we get a NameError in that case.
Dictionary Operators and Built-in Functions
Let’s talk about two important operators and built-in functions we can use with dictionaries.
len() function
The len() function returns the number of key-value pairs in a dictionary:
sorted() function
The sorted() function sorts the elements of a given iterable in a specific order (ascending or descending) and returns it as a list.
>>> sorted(my_dict) ['Name', 'Roll', 'Subjects']
in operator
You can use the in operator to check whether a key is present in the dictionary or not.
>>> 'Roll' in my_dict True >>> 'College' in my_dict False
Built-in Dictionary Methods
There are various built-in methods available in a Python dictionary. We have discussed few of them earlier such as clear() , pop() ,and popitem() . Let’s see some other methods too.
Method | Description |
---|---|
clear() | Removes all items from the dictionary. |
copy() | Returns a shallow copy of the dictionary. |
fromkeys(seq[, v]) | Returns a new dictionary with keys from seq and value equal to v (defaults to None ). |
get(key[,d]) | Returns the value of the key . If the key does not exist, returns d (defaults to None ). |
items() | Return a new object of the dictionary’s items in (key, value) format. |
keys() | Returns a new object of the dictionary’s keys. |
pop(key[,d]) | Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises KeyError . |
popitem() | Removes and returns an arbitrary item (key, value). Raises KeyError if the dictionary is empty. |
setdefault(key[,d]) | Returns the corresponding value if the key is in the dictionary. If not, inserts the key with a value of d and returns d (defaults to None ). |
update([other]) | Updates the dictionary with the key/value pairs from other , overwriting existing keys. |
values() | Returns a new object of the dictionary’s values |
How to iterate through a dictionary
By default, when we use a for loop to iterate over a dictionary, we get the keys:
my_dict = < "Name": "Ashutosh Krishna", "Roll": 23, "Subjects": ["OS", "CN", "DBMS"] >for item in my_dict: print(item)
We can also iterate over a dictionary in the following ways:
How to iterate through a dictionary using the items() method
When we use the items() method to iterate over a dictionary, it returns a tuple of key and value in each iteration. Thus we can directly get the key and value in this case:
my_dict = < "Name": "Ashutosh Krishna", "Roll": 23, "Subjects": ["OS", "CN", "DBMS"] >for key, value in my_dict.items(): print(key, value)
Name Ashutosh Krishna Roll 23 Subjects ['OS', 'CN', 'DBMS']
How to iterate through a dictionary using keys()
In this case, we get the key in each iteration.
my_dict = < "Name": "Ashutosh Krishna", "Roll": 23, "Subjects": ["OS", "CN", "DBMS"] >for key in my_dict.keys(): print(key)
How to iterate through a dictionary using values()
In this case, we get the values of the dictionary directly.
my_dict = < "Name": "Ashutosh Krishna", "Roll": 23, "Subjects": ["OS", "CN", "DBMS"] >for value in my_dict.values(): print(value)
Ashutosh Krishna 23 ['OS', 'CN', 'DBMS']
How to merge dictionaries in Python
We often need to merge dictionaries in Python. I’ve written a separate article on this topic, which you can read here.
Wrapping Up
In this article, we learned what Python dictionaries are and how to perform CRUD operations on them. We also saw several methods and functions associated with them.
I hope you enjoyed it – and thanks for reading!