Python Dictionary: Everything You Need To Know [With Examples]
By Rohit Sharma
Updated on Dec 21, 2023 | 8 min read | 6.2k views
Share:
For working professionals
For fresh graduates
More
By Rohit Sharma
Updated on Dec 21, 2023 | 8 min read | 6.2k views
Share:
Table of Contents
If you’re working with Python, you must have heard of lists, strings, and tuples. Today, we’re going to talk about another crucial element of Python – dictionary. After you’re done reading this post, you should have a relatively good understanding of Python dictionaries, how to create them, and how to use them.
In Python, a dictionary is an implementation of a data structure that is usually known as an associative array. It contains an unorganized collection of data values (for example, a map). However, unlike other data types that contain only a single value as an element, the data values stored in a dictionary hold a key:value pair. This helps optimize the dictionary. Each key: value pair maps the unique key associated with its value.
In a Python dictionary, keys are unique, but the values may or may not be – while the keys must be of an immutable data type (strings, numbers, and tuples), values can be of any type. Also, in a Python dictionary, the keys are case sensitive. So, keys having the same name, but different cases are treated differently.
Learn more about: Python Data Types
Learn data science course from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
In Python, dictionaries and lists share both similarities and differences. The common traits shared by dictionaries and lists include:
The main difference between dictionaries and lists is that while list elements can be accessed (based on their position in the list) via indexing, dictionary elements are accessed via keys.
Check out All Python tutorial concepts Explained with Examples.
Now, we’ll discuss some of the most commonly used methods in Python dictionaries.
update([other]) – It updates the dictionary with the key/value pairs from other by overwriting the existing keys.
upGrad’s Exclusive Data Science Webinar for you –
You can create a Python dictionary by enclosing a comma-separated list of key-value pairs in curly braces { }. A colon “:” separates each key from its associated value:
d = {
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}
You can also use the built-in function dict( ) to create a dictionary, like so:
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: ‘apple’, 2: ‘ball’}
# dictionary with mixed keys
my_dict = {‘name’: ‘John’, 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:’apple’, 2:’ball’})
# from sequence having each item as a pair
my_dict = dict([(1,’apple’), (2,’ball’)])
Here’s an example of a code used to access elements from a dictionary:
#!/usr/bin/python
dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}
print “dict[‘Name’]: “, dict[‘Name’]
print “dict[‘Age’]: “, dict[‘Age’]
For example, dict[key] = ‘value’. To update an existing value in a dictionary, you have to use the built-in update( ) method. You must remember that while adding a value to a dictionary if the value already exists, the value gets updated otherwise a new key with the value is added to the dictionary.
my_dict = {‘name’:’Jack’, ‘age’: 26}
# update value
my_dict[‘age’] = 27
#Output: {‘age’: 27, ‘name’: ‘Jack’}
print(my_dict)
# add item
my_dict[‘address’] = ‘Downtown’
# Output: {‘address’: ‘Downtown’, ‘age’: 27, ‘name’: ‘Jack’}
print(my_dict)
To remove or delete an item from a dictionary, you can use the pop ( ) method. It will remove the particular item with the provided ket and return the value. You can also use the popitem( )method to delete and return an arbitrary element (key and value) from the dictionary.
If you want to delete all the items at once, you can use the clear( ) method. You can also use the del keyword to remove individual items or the del dict ( ) method to delete the entire dictionary itself.
An example using the del dict ( ) method:
#!/usr/bin/python
dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}
del dict[‘Name’]; # remove entry with key ‘Name’
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print “dict[‘Age’]: “, dict[‘Age’]
print “dict[‘School’]: “, dict[‘School’]
Also learn: Python Developer Salary in India
In a Python dictionary, you can loop through using a for loop. When you loop through a dictionary, the keys of the dictionary are the return value.
An example of looping through a dictionary is:
for x in thisdict:
print(x)
Read: Most Important Python Functions
You can use the “in” keyword to check if a specific key is present in the dictionary, like so:
thisdict = {
“brand”: “Ferrari”,
“model”: “Daytone”,
“year”: “1968”
}
if “model” in thisdict:
print(“Yes, ‘model’ is one of the keys in the thisdict dictionary”)
You can set the length of a dictionary, that is, determine how many elements (key:value pairs) it will have, using the len( ) method, like so:
print(len(thisdict))
You can copy a dictionary using the built-in copy( ) method. However, you cannot copy a dictionary by typing dict2 = dict1 because dict2 will only be a reference to dict1.
Here’s an example using the copy( ) method:
thisdict = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
mydict = thisdict.copy()
print(mydict)
In Python, dictionary comprehension is a straightforward and neat way of creating a new dictionary from an iterable. It consists of an expression pair (key: value) followed by for statement inside curly braces { }. Dictionary comprehension can contain multiple for or if statements.
Here’s an example for creating a dictionary where each item is a pair of a number and its square:
squares = {x: x*x for x in range(6)}
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares)
Read more: Python Data Visualization Libraries
That’s it basically – all the fundamental knowledge you need to know about Python dictionary!
If you are curious to learn about Python, everything about Data science, check out upGrad’s Data Science Certification Courses which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources