We may not have the course you’re looking for. If you enquire or give us a call on 0800 446148 and speak to our training experts, we may still be able to help with your training requirements.
Training Outcomes Within Your Budget!
We ensure quality, budget-alignment, and timely delivery by our expert instructors.
Python, a popular programming language, consists of many tools and features. One such feature is called a Python Dictionary, which is a collection of unique key-value pairs utilised to store data values. In this blog on Python Dictionary, we will learn what is a Dictionary in Python, how to create it, and other important aspects related to Python Dictionary.
Table of Contents
1) What is a Python Dictionary?
2) Creating a Dictionary
3) Adding elements to a Dictionary
4) Accessing elements of a Dictionary
5) Dictionary methods
6) Conclusion
What is a Python Dictionary?
In Python, a Dictionary is similar to a database that stores items in key-value pairs. A ‘key’ acts as a unique identifier for an item, and a value is the data related to that key. Dictionaries are often utilised to store information like words and definitions but can also be used to store other types of information. Dictionaries, in Python, are defined as mutable. This means that they can be modified after they are created. Dictionaries are also unordered, meaning the items are not stored in any particular order.
Here is an example of a Dictionary in Python:
# Creating a Dictionary student = { 'name': 'Alice', 'age': 20, 'grade': 'A', 'courses': ['Math', 'Physics', 'History'] } # Accessing values using keys print("Student Name:", student['name']) print("Student Age:", student['age']) print("Student Grade:", student['grade']) print("Student Courses:", student['courses']) |
Output:
Student Name: Alice
Student Age: 20
Student Grade: A
Student Courses: ['Math', 'Physics', 'History']
In this example, we created a Dictionary called 'student' with keys 'name', 'age', 'grade', and 'courses', each associated with a specific value. We then accessed these values using the keys, and you can see the output displaying the corresponding information.
Enhance your career prospects by learning Programming focused on your domain; sign up for our Programming Training now!
Creating a Dictionary
Creating a Dictionary in Python is done by enclosing a sequence of elements in curly braces {}. The elements are separated by a comma. In a Dictionary, each pair of values consists of a Key, followed by its corresponding value separated by a colon. The values in a Dictionary can be of any data type and can be repeated. However, the keys must be unique and cannot be changed.
Here is an example to create a Dictionary in Python:
# Creating a Dictionary student = { "name": "John", "age": 20, "grade": "A" } # Accessing Dictionary values print("Name:", student["name"]) print("Age:", student["age"]) print("Grade:", student["grade"]) |
Output:
Name: John
Age: 20
Grade: A
In this example, we create a Dictionary called 'student' with three key-value pairs. Each key (e.g., "name", "age", "grade") is associated with a value (e.g., "John", 20, "A"). We then access and print these values using the keys.
In Python, creating a Dictionary can also be implemented with the built-in function dict(). Here is an example:
# Creating a Dictionary using dict() function with keyword arguments student = dict(name="John", age=20, grade="A")
# Accessing Dictionary values print("Name:", student["name"]) print("Age:", student["age"]) print("Grade:", student["grade"]) |
Output:
Name: John
Age: 20
Grade: A
In this example, we use the 'dict()' function with keyword arguments to create a Dictionary called 'student'. Each keyword argument represents a key-value pair in the Dictionary. The keys (e.g., "name", "age", "grade") are specified as keywords, and the corresponding values are provided.
Learn Python framework for creating websites, sign up for our Python Django Training now!
Adding elements to a Dictionary
There are various ways to add elements to a Dictionary. One can add a single value at a time by specifying the key and its corresponding value, like this: Dict[Key] = 'Value'. To update an existing value in a Dictionary, one can use the built-in ‘update()’ method. In addition, nested key values can also be added to an existing Dictionary. It is worth noting that if a key-value pair already exists, the value will be updated; otherwise, a new key-value pair will be added to the Dictionary.
Let us understand it better with the help of an example:
# Creating an empty Dictionary student = {} # Adding elements to the Dictionary student["name"] = "John" student["age"] = 20 student["grade"] = "A" # Displaying the Dictionary after initial additions print("After initial additions:") print(student) # Adding a set of values to an existing key student["courses"] = ["Math", "Science", "History"] # Updating an existing key's value student["age"] = 21 # Adding a nested key-value pair to the Dictionary student["address"] = { "street": "123 Main St", "city": "Anytown", "state": "CA" } # Displaying the Dictionary after all operations print("nAfter adding a set of values, updating, and adding a nested key-value pair:") print(student) |
Output:
After initial additions:
{'name': 'John', 'age': 20, 'grade': 'A'}
After adding a set of values, updating, and adding a nested key-value pair:
{'name': 'John', 'age': 21, 'grade': 'A', 'courses': ['Math', 'Science', 'History'], 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA'}}
In the above example:
a) We start with an empty Dictionary, ‘student,’ and add initial elements.
b) We add a set of values (a list of courses) to an existing key "courses".
c) We update the age from 20 to 21 by assigning a new value to the "age" key.
d) We add a nested key-value pair "address," which contains another Dictionary with address details.
e) Finally, we print the Dictionary after all these operations to see the updated content.
Gain knowledge of the working of Lua programming language, sign up for our Lua Programming Language Training now!
Accessing elements of a Dictionary
Accessing elements of a Dictionary can be implemented by a key and not by an index. This means that an element in a Dictionary cannot be accessed using its position but with the Dictionary key. Let us understand this with the help of an example:
# Creating a Dictionary student = { "name": "John", "age": 20, "grade": "A" } # Accessing Dictionary elements name = student["name"] age = student["age"] grade = student["grade"] # Displaying the accessed elements print("Name:", name) print("Age:", age) print("Grade:", grade) |
Output:
Name: John
Age: 20
Grade: A
In this example, we have a Dictionary called 'student' with three key-value pairs. We access the elements by using the keys as indices ("name", "age", and "grade") and assign them to variables ('name', 'age', and 'grade'). Then, we print out the values of these variables, which correspond to the values in the Dictionary.
Accessing an element with ‘get()’
Accessing an element can also be implemented using a method called 'get()'. Let us refer to an example to know how to use 'get()':
# Creating a Dictionary student = { "name": "John", "age": 20, "grade": "A" } # Accessing Dictionary elements using get() name = student.get("name", "Name not found") major = student.get("major", "Major not found") # Displaying the accessed elements print("Name:", name) print("Major:", major) |
Output:
Name: John
Major: Major not found
In the above example:
a) We have a Dictionary called 'student' with three key-value pairs.
b) We use the 'get()' method to access elements. When we use 'student.get("name", "Name not found")', it returns the value associated with the key "name" ("John" in this case). However, when we use 'student.get("major", "Major not found")', the key "major" does not exist in the Dictionary, so it returns the default value "Major not found."
Accessing an element of a nested Dictionary
Accessing an element of a nested Dictionary can be implemented with indexing [] syntax. Let us refer to an example to understand it:
# Creating a nested Dictionary student = { "name": "John", "age": 20, "grades": { "math": 90, "science": 85, "history": 92 } } # Accessing an element of the nested Dictionary math_grade = student["grades"]["math"] # Displaying the accessed element print("Math Grade:", math_grade) |
Output:
Math Grade: 90
In the above example:
a) We have a nested Dictionary called 'student', where the "grades" key maps to another Dictionary containing subject grades.
b) To access the math grade, we first use "grades" as the key to access the inner Dictionary, and then we use "math" as the key to access the math grade.
c) Finally, we print the math grade, which is 90.
Learn PHP skills for web development, sign up for our PHP Programming Training now!
Dictionary methods
Python provides multiple built-in methods to manipulate Dictionaries. These methods are utilised for adding, removing, and changing values of Dictionary keys. Dictionary methods are a robust way to work with Dictionaries. Understanding these methods becomes essential in working with Dictionaries effectively to store and manipulate data.
Method |
Description |
dic.clear() |
Removes the entire elements from the Dictionary |
dict.copy() |
Provides a copy of the Dictionary |
dict.get(key, default = “None”) |
Provides the value of specified key |
dict.items() |
Provides a list containing a tuple for each key value pair |
dict.keys() |
Provides a list containing Dictionary's keys |
dict.update(dict2) |
Updates specified key-value pairs in the Dictionary |
dict.values() |
Provides a list of all the values of the Dictionary |
pop() |
With specified key, removes the element |
popItem() |
Removes the previously inserted key-value pair |
dict.setdefault(key,default= “None”) |
Sets the key to the default value if the key is not specified in the Dictionary |
dict.has_key(key) |
Provides ‘true’ if the Dictionary contains the specified key |
dict.get(key, default = “None”) |
Provides the value specified for the passed key |
Let us understand Dictionary methods with the help of an example:
# Creating a Dictionary student = { "name": "John", "age": 20, "grade": "A" } # Using various Dictionary methods # 1. clear() - Removes all items from the Dictionary student.clear() # 2. copy() - Creates a shallow copy of the Dictionary student_copy = student.copy() # 3. get() - Retrieves the value for a key with a default value grade = student.get("grade", "Not found") # 4. items() - Returns a list of key-value pairs as tuples student_items = student_copy.items() # 5. keys() - Returns a list of Dictionary keys student_keys = student_copy.keys() # 6. update() - Updates the Dictionary with another Dictionary student_copy.update({"major": "Computer Science"}) # 7. values() - Returns a list of Dictionary values student_values = student_copy.values() # Displaying the results print("After using Dictionary methods:") print("Student:", student) print("Student Copy:", student_copy) print("Grade:", grade) print("Student Items:", student_items) print("Student Keys:", student_keys) print("Student Values:", student_values) |
Output:
After using Dictionary methods:
Student: {}
Student Copy: {'major': 'Computer Science'}
Grade: Not found
Student Items: dict_items([('major', 'Computer Science')])
Student Keys: dict_keys(['major'])
Student Values: dict_values(['Computer Science'])
From the above example:
a) 'clear()' removes all items from the 'student' Dictionary
b) 'copy()' creates a shallow copy of the 'student' Dictionary into 'student_copy'
c) 'get("grade", "Not found")' retrieves the value associated with the key "grade", but since the Dictionary is empty, it returns the default value "Not found."
d) 'items()' returns a list of key-value pairs as tuples from the 'student_copy' Dictionary
e) 'keys()' returns a list of keys from the 'student_copy' Dictionary
f) 'update({"major": "Computer Science"})' updates the 'student_copy' Dictionary with a new key-value pair
g) 'values()' returns a list of values from the 'student_copy' Dictionary
Conclusion
Python is widely considered one of the most popular programming languages since it offers a variety of features. Its structured code and numerous built-in features make it easier to comprehend various aspects of programming. The Python Dictionary is among such features that allow you to access and store data, providing a versatile coding experience.
Acquire knowledge about the architecture, data model and installation of Cassandra, sign up for our Apache Cassandra Training now!
Frequently Asked Questions
Upcoming Programming & DevOps Resources Batches & Dates
Date
Thu 23rd Jan 2025
Thu 27th Feb 2025
Thu 27th Mar 2025
Thu 29th May 2025
Thu 3rd Jul 2025
Thu 4th Sep 2025
Thu 6th Nov 2025