We may not have the course you’re looking for. If you enquire or give us a call on +60 1800812339 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.
Have you ever needed a smart and simple way to store information but struggled to keep it organised? Enter Python Dictionaries! Think of them as a magical box where each item has a unique label, allowing you to find exactly what you need instantly. Python Dictionaries store data as key-value pairs, making it easy to retrieve, modify, and add information.
In this blog, we’ll dive into the world of Python Dictionaries. You’ll learn how to create, access, modify, add, and remove elements while also exploring key restrictions and essential dictionary methods. Ready to unlock the full potential of Python’s most flexible data structure? Let’s get started!
Table of Contents
1) What are Python Dictionaries?
2) Creating a Dictionary in Python
3) Accessing Elements of a Dictionary
4) Adding Elements to a Python Dictionary
5) Modifying Elements in a Python Dictionary
6) Removing Elements from a Python Dictionary
7) Restrictions on Python Dictionary Keys and Values
8) Dictionary Methods
9) Conclusion
What are Python Dictionaries?
Python Dictionaries are a versatile and powerful data structure in Python. They store data in key-value pairs, allowing for efficient data retrieval. Here’s a quick overview:
Key Features of Python Dictionaries:
a) Key-Value Pairs: Each element in a dictionary is a pair consisting of a unique key and a value.
b) Mutable: You can change, add, or remove items after the dictionary is created.
c) Unordered: The items are not stored in any particular order.
d) Dynamic: They can grow and shrink as needed.
Here’s a basic example:
person = { "name": "Alice", "age": 30, "city": "New York" } |
In this dictionary:
a) "name", "age", and "city" are the keys.
b) "Alice", 30, and "New York" are associated values.
Python Dictionaries are particularly useful when you want to access elements by a unique identifier (key) rather than by an index (like in lists or tuples).
Creating a Dictionary in Python
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 an empty dictionary my_dict = {} # Creating a dictionary with initial values my_dict = { "name": "Alice", "age": 25, "city": "New York" } # Accessing values print(my_dict["name"]) # Output: Alice # Adding a new key-value pair my_dict["email"] = "[email protected]" # Updating an existing value my_dict["age"] = 26 # Removing a key-value pair del my_dict["city"] # Iterating through the dictionary for key, value in my_dict.items(): print(f"{key}: {value}") |
Output:
Alice name: Alice age: 26 email: [email protected] |
Elevate your skills with our Python Django Training - join now for in-depth learning!
Accessing elements of a Dictionary
Accessing elements of a Dictionary can be done 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!
Adding Elements to a Python Dictionary
To add elements to a dictionary by assigning a value to a new key. If the key already exists, its value will be updated.
Example:
person = {'name': 'Emma', 'age': 30} # Adding a new key-value pair person['city'] = 'New York' # Retrieving values and handling missing key with default name = person.get('name') city = person.get('city') major = person.get('major', 'Major not found') # Printing in the desired format print(f"Name: {name}nCity: {city}nMajor: {major}") |
Output:
Name: Emma City: New York Major: Major not found |
Explanation:
a) The new key 'city' with the value 'New York' is added to the dictionary.
b) The key 'major' doesn't exist, so the default message 'Major not found' is printed.
Modifying Elements in a Python Dictionary
To modify an element, simply assign a new value to an existing key. This will overwrite the old value.
Example:
employee = {'name': 'Sarah', 'position': 'Analyst'} # Modifying an existing value employee['position'] = 'Senior Analyst' # Retrieving values and handling missing key with default name = employee.get('name') position = employee.get('position') department = employee.get('department', 'Department not assigned') # Printing in the desired format print(f"Name: {name}nPosition: {position}nDepartment: {department}") |
Output:
Name: Sarah Position: Senior Analyst Department: Department not assigned |
Explanation:
a) The value of the key 'position' is modified from 'Analyst' to 'Senior Analyst'.
b) The key 'department' doesn't exist, so the default message 'Department not assigned' is printed.
Removing Elements from a Python Dictionary
To remove elements using the del statement or the pop() method.
Example:
car = {'brand': 'Toyota', 'model': 'Corolla', 'year': 2015} # Removing an existing key-value pair del car['year'] # Retrieving values and handling missing key with default brand = car.get('brand') year = car.get('year', 'Year information not available') # Printing in the desired format print(f"Brand: {brand}nYear: {year}") |
Output:
Brand: Toyota Year: Year information not available |
Explanation:
a) The key 'year' is removed from the dictionary.
b) Since 'year' no longer exists, the default message 'Year information not available' is printed.
Boost your career with Object Oriented Programming (OOPs) Course - register today for success!
Restrictions on Python Dictionary Keys and Values
Python Dictionaries have certain restrictions for keys and values, which must be followed for the dictionary to function properly. Let’s explore them in more detail.
a) Restrictions on Dictionary Keys
When working with Python Dictionaries, it's important to know that not all data types can be used as keys. There are specific rules governing which types are allowed. Let’s explore the restrictions on dictionary keys and why they exist to ensure smooth functionality in Python Dictionaries.
1) Keys Must be Immutable:
Dictionary keys must be of an immutable data type, meaning they cannot be changed after being created. Immutable types include:
a) Strings (str)
b) Numbers (int, float)
c) Tuples (tuple)
Example:
my_dict = {'name': 'Alice', 42: 'Age', (1, 2): 'Coordinates'} # Retrieving values to display name = my_dict.get('name') age = my_dict.get(42) coordinates = my_dict.get((1, 2)) print(f"Name: {name}nAge: {age}nCoordinates: {coordinates}") |
Output:
Name: Alice Age: Age Coordinates: Coordinates |
2) Keys Must Be Unique:
In a dictionary, keys must be unique. If you use the same key more than once, the last value assigned to that key will overwrite the previous value.
Example:
my_dict = {'name': 'Alice', 'name': 'Bob'} # 'Bob' will overwrite 'Alice' # Retrieving the overwritten key name = my_dict.get('name') print(f"Name: {name}") |
Output:
Name: Bob |
b) Restrictions on Dictionary Values
Unlike keys, dictionary values have fewer restrictions. However, understanding the flexibility and limitations of values in Python Dictionaries can help you manage your data efficiently. Let’s look into the guidelines for using values in dictionaries.
1) Values can be of any Data Type:
Unlike keys, values in a dictionary can be of any data type. You can have strings, integers, lists, or even other dictionaries as values.
Example:
my_dict = {'name': 'Alice', 'age': 30, 'skills': ['Python', 'Java']} # Retrieving values to display name = my_dict.get('name') age = my_dict.get('age') skills = my_dict.get('skills') print(f"Name: {name}nAge: {age}nSkills: {skills}") |
Output:
Name: Alice Age: 30 Skills: ['Python', 'Java'] |
2) Values can be Mutable:
Dictionary values can be mutable, which means you can use lists, dictionaries, and other mutable types as dictionary values.
Example:
my_dict = {'name': 'Alice', 'projects': ['Project1', 'Project2']} # Modifying the list (mutable value) my_dict['projects'].append('Project3') # Retrieving values to display name = my_dict.get('name') projects = my_dict.get('projects') print(f"Name: {name}nProjects: {projects}") |
Output:
Name: Alice Projects: ['Project1', 'Project2', 'Project3'] |
3) Values can be Duplicated:
Unlike keys, values in a dictionary do not have to be unique. You can have the same value assigned to different keys.
Example:
my_dict = {'name': 'Alice', 'city': 'London', 'country': 'London'} # Retrieving values to display name = my_dict.get('name') city = my_dict.get('city') country = my_dict.get('country') print(f"Name: {name}nCity: {city}nCountry: {country}") |
Output:
Name: Alice City: London Country: London |
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.
1) dict.get(key, default=None)
Retrieves the value of the specified key. If the key does not exist, it returns the default value (which is None by default).
Example:
my_dict = {'name': 'Alice', 'age': 30} # Using get method to retrieve values name = my_dict.get('name') city = my_dict.get('city', 'City not found') # Printing the result print(f"Name: {name}nCity: {city}") |
Output:
Name: Alice City: City not found |
2) dict.keys()
Returns a view object containing all the keys in the dictionary.
Example:
book = {'title': '1984', 'author': 'George Orwell'} # Using keys() method to get all keys keys = list(book.keys()) # Printing the result in the desired format print(f"First Key: {keys[0]}nSecond Key: {keys[1]}") Output: First Key: title Second Key: author |
3) dict.values()
Returns a view object containing all the values in the dictionary.
Example:
student = {'name': 'John', 'grade': 'A'} # Using values() method to get all values values = list(student.values()) # Printing the result in the desired format print(f"Name: {values[0]}nGrade: {values[1]}") |
Output:
Name: John Grade: A |
4) dict.items()
Returns a view object that displays a list of dictionary’s key-value pairs as tuples.
Example:
employee = {'name': 'Sarah', 'position': 'Manager'} # Using items() method to get all key-value pairs items = list(employee.items()) # Printing the result in the desired format print(f"Name: {items[0][1]}nPosition: {items[1][1]}") |
Output:
Name: Sarah Position: Manager |
5) dict.pop(key, default=None)
Removes and returns the value associated with the specified key. If the key doesn’t exist, the default value is returned. If no default is provided, it raises a KeyError.
Example:
person = {'name': 'David', 'age': 40, 'city': 'New York'} # Using pop() to remove the 'city' key and get its value city = person.pop('city', 'City not found') # Printing the result in the desired format print(f"Name: {person.get('name')}nCity: {city}") |
Output:
Name: David City: New York |
6) dict.popitem()
Removes and returns the last key-value pair inserted into the dictionary as a tuple. It raises a KeyError if the dictionary is empty.
Example:
fruit = {'name': 'Apple', 'color': 'Red'} # Using popitem() to remove the last inserted item last_item = fruit.popitem() # Printing the result in the desired format print(f"Name: {fruit.get('name')}nColor: {last_item[1]}") |
Output:
Name: Apple Color: Red |
7) dict.update([other])
Updates the dictionary with elements from another dictionary or an iterable of key-value pairs. Existing keys will have their values updated, and new keys will be added.
Example:
computer = {'brand': 'Dell'} # Using update() to add or modify key-value pairs computer.update({'model': 'XPS', 'year': 2021}) # Printing the result in the desired format print(f"Brand: {computer.get('brand')}nModel: {computer.get('model')}") |
Output:
Brand: Dell Model: XPS |
8) dict.clear()
Removes all elements from the dictionary, leaving it empty.
Example:
inventory = {'item': 'Laptop', 'quantity': 5} # Using clear() to remove all items inventory.clear() # Printing the result in the desired format print(f"Item: {inventory.get('item', 'Item not found')}nQuantity: {inventory.get('quantity', 'Quantity not found')}") |
Output:
Item: Item not found Quantity: Quantity not found |
9) dict.copy()
Returns a shallow copy of the dictionary.
Example:
vehicle = {'type': 'Car', 'brand': 'Ford'} # Using copy() to create a shallow copy vehicle_copy = vehicle.copy() # Printing the result in the desired format print(f"Type: {vehicle_copy.get('type')}nBrand: {vehicle_copy.get('brand')}") |
Output:
Type: Car Brand: Ford |
10) dict.setdefault(key, default=None)
Returns the value of the specified key if it exists. If the key does not exist, it inserts the key with the specified default value and returns the default.
Example:
dog = {'name': 'Buddy'}
# Using setdefault() to set a default value for 'breed' breed = dog.setdefault('breed', 'Breed not available')
# Printing the result in the desired format print(f"Name: {dog.get('name')}nBreed: {breed}") |
Output:
Name: Buddy Breed: Breed not available |
Advance your career with comprehensive Programming Training - start learning today!
Conclusion
Python Dictionaries provide a versatile and efficient way to store and manage data through key-value pairs. By mastering their creation, modification, and key-value handling, you can streamline your coding tasks. Embrace the full potential of Dictionaries in Python and elevate your programming efficiency.
Enhance your skills with our comprehensive R Programming Course - join now!
Frequently Asked Questions
To print a dictionary in Python, you can use the `print()` function, which displays the dictionary in a readable key-value format. This makes it easy to view its contents directly.
To declare a dictionary in Python, use curly braces `{}` to define key-value pairs separated by colons. For example, a dictionary is written as `my_dict = {'key': 'value'}`.
The Knowledge Academy takes global learning to new heights, offering over 30,000 online courses across 490+ locations in 220 countries. This expansive reach ensures accessibility and convenience for learners worldwide.
Alongside our diverse Online Course Catalogue, encompassing 19 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. Tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA.
The Knowledge Academy’s Knowledge Pass, a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds.
The Knowledge Academy offers various Programming Training, including Python Course, PHP Course, Python Django Training, R Programming Course and Visual Basic Course. These courses cater to different skill levels, providing comprehensive insights into Phases of Compiler.
Our Programming & DevOps Blogs cover a range of topics related to Python, offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your programming skills, The Knowledge Academy's diverse courses and informative blogs have got you covered.
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