Dictionaries are used to store data values in key:value pairs and written with curly brackets, where each key is unique and maps to a value.
student = {
"name": "Deepak",
"age": 25,
"course": "Python"
}
print(student)
From Python's perspective, dictionaries are defined as objects with the data type <class 'dict'>
my_dict = {"name": "Deepak", "age": 21}
print(type(my_dict))
Starting from Python 3.7, dictionaries maintain the insertion order of items. This means the order in which items are added to the dictionary is preserved.
my_dict = {"name": "Deepak", "age": 21, "course": "Python"}
for key, value in my_dict.items():
print(key, value)
Dictionaries in Python do not allow duplicate keys. Values can be duplicates. If you try to insert a duplicate key, the value of the key is overwritten with the new value.
my_dict = {"name": "Deepak", "age": 21, "nickname": "Deepak"}
# Adding a duplicate key with a new value
my_dict["name"] = "Raj"
# Printing the updated dictionary
print(my_dict)
A Python Dictionary allows you to store values of any data type as values, while the keys must be of an immutable data type (e.g., strings, numbers, tuples).
π Key Data Types :
# Valid keys: string, integer, tuple
my_dict = {
"name": "Deepak", # String as key
42: "Answer", # Integer as key
(1, 2): "Tuple Key" # Tuple as key
}
print(my_dict)
π Value Data Types
my_dict = {
"name": "Deepak", # String value
"age": 21, # Integer value
"hobbies": ["coding", "reading"], # List as value
"address": {"city": "Delhi", "state": "Delhi"} # Dictionary as value
}
print(my_dict)
Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.
student = {"name": "Deepak", "age": 21}
student["course"] = "Python" # Add a new key-value pair
student["age"] = 25 # Update an existing value
del student["name"] # Delete a key-value pair
print(student)
You can find the number of key-value pairs in a dictionary using the built-in len() function.
student = {
"name": "Deepak",
"age": 21,
"course": "Python"
}
print(len(student))
Python provides a built-in dict() constructor to create dictionaries in a clean and flexible way.
Using Keyword Arguments
student = dict(name="Deepak", age=21, course="Python")
print(student)
Using List of Tuples
student = dict([("name", "Deepak"), ("age", 21), ("course", "Python")])
print(student)
Using Tuple of List
data = (["name", "Deepak"], ["age", 21])
d = dict(data)
print(d)
Using Zipped Lists
keys = ["name", "age", "course"]
values = ["Deepak", 21, "Python"]
student = dict(zip(keys, values))
print(student)
A nested dictionary is a dictionary inside another dictionary.
myfamily = {
"child1": {
"name": "Aarav",
"age": 15
},
"child2": {
"name": "Ishita",
"age": 13
},
"child3": {
"name": "Kabir",
"age": 11
}
}
You can access the items of a dictionary by referring to its key name, inside square [ ]brackets:
Note: If the key doesnβt exist, it raises a β KeyError.
student = {"name": "Deepak", "age": 21}
print(student["name"])
Adding items to a dictionary is simple β just assign a new key-value pair.
student = {"name": "Deepak", "age": 21}
student["course"] = "A Level"
print(student)
You can update or modify existing dictionary values using their keys.
student = {"name": "Deepak", "age": 21}
student["age"] = 25
print(student)
The del keyword removes the specific item with the specified key name or deletes the entire dictionary.
student = {"name": "Deepak", "age": 21}
del student["name"]
print(student)
del student
print(student)
Traversing a dictionary means looping through its keys, values, or both by using a for loop.
β 1. Loop Through Keys
student = {"name": "Deepak", "age": 25, "city": "Sultanpur"}
for key in student:
print(key)
β 2. Loop Through Values
student = {"name": "Deepak", "age": 25, "city": "Sultanpur"}
for key in student:
print(student[key])
β 3. Loop Through Keys and Values
student = {"name": "Deepak", "age": 25, "city": "Sultanpur"}
for key in student:
print(key, ":", student[key])
You can sort a dictionary in Python by keys or values, in ascending or descending order using the built-in sorted() function.
β Sort by Keys Ascending Order
students = {'Riya': 25, 'Amit': 22, 'Neha': 21, 'Kabir': 26}
for key in sorted(students):
print(key,' : ',students[key])
β Sort by Keys Descending Order
students = {'Riya': 25, 'Amit': 22, 'Neha': 21, 'Kabir': 26}
for key in sorted(students, reverse=True):
print(key,' : ',students[key])
β Sort by Values Ascending Order
students = {'Riya': 25, 'Amit': 22, 'Neha': 21, 'Kabir': 26}
for key in sorted(students, key=students.get):
print(key,':',students[key])
β Sort by Values Descending Order
students = {'Riya': 25, 'Amit': 22, 'Neha': 21, 'Kabir': 26}
for key in sorted(students, key=students.get, reverse=True):
print(key,':',students[key])
Python has a set of built-in methods that you can use on dictionaries.
| Method | Description | Example |
|---|---|---|
| get() | Returns value of specified key | d.get('name') |
| keys() | Returns all keys | d.keys() |
| values() | Returns all values | d.values() |
| items() | Returns key-value pairs | d.items() |
| update() | Updates with given dict | d.update({'age': 25}) |
| setdefault() | Get or set default value | d.setdefault('city','Delhi') |
| pop() | Removes key and returns value | d.pop('name') |
| popitem() | Removes last item | d.popitem() |
| clear() | Empties the dictionary | d.clear() |
| copy() | Returns shallow copy | new_d = d.copy() |
| fromkeys() | New dict from keys | dict.fromkeys(['a','b'], 0) |
Safely retrieve the value of a key from a dictionary. If the key is not found, it returns None or a specified default value.
Syntax : dictionary.get(key, default_value)
student = {'name': 'Ravi', 'age': 21}
# Existing key
print(student.get('name'))
# Non-existing key without default
print(student.get('grade'))
# Non-existing key with default
print(student.get('grade', 'A'))
The keys() method returns a view object. The view object contains the keys of the dictionary, as a list.
Syntax : dictionary.keys()
student = {'name': 'Ravi', 'age': 21, 'grade': 'A'}
print(student.keys())
The values() method returns a view object. The view object contains the values of the dictionary, as a list.
Syntax : dictionary.values()
student = {'name': 'Ravi', 'age': 21, 'grade': 'A'}
print(student.values())
The items() method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list.
Syntax : dictionary.items()
student = {'name': 'Ravi', 'age': 21, 'grade': 'A'}
print(student.items())
The update() method allows you to add or update key-value pairs in the dictionary.
π If the key already exists, its value will be updated.
π If the key doesn't exist, the key-value pair is added.
Syntax : dictionary.update(iterable)
student = {'name': 'Ravi', 'age': 21}
# Adding a new key-value pair
student.update({'grade': 'A'})
print(student)
# Updating an existing key-value pair
student.update({'age': 22})
print(student)
# Update with another dictionary
student.update({'city': 'Delhi', 'country': 'India'})
print(student)
The setdefault() method returns the value of a specified key.
If the key does not exist, it adds the key with a default value.
Syntax : dictionary.setdefault(key, default_value)
student = {'name': 'Ravi', 'age': 21}
# Existing key β returns current value
print(student.setdefault('name'))
# Non-existing key β adds with default None
print(student.setdefault('course'))
# Non-existing key β adds with default value
print(student.setdefault('grade', 'A'))
print(student)
Removes the specified key and returns its value. If the key is not found, it raises a KeyError when default value is not given.
Syntax : dictionary.pop(key, default_value)
student = {'name': 'Ravi', 'age': 21, 'grade': 'A'}
# Removing an existing key
age = student.pop('age')
print(age)
print(student)
# Removing a non-existing key with default
city = student.pop('city', 'Not Found')
print(city)
# Removing a non-existing key without default
student.pop('city') # β This will raise KeyError
Removes and returns the last inserted key-value pair as a tuple.
Syntax : dictionary.popitem()
student = {'name': 'Ravi', 'age': 21, 'grade': 'A'}
last_item = student.popitem()
print(last_item)
print(student)
{}.popitem() # β KeyError
Removes all key-value pairs from the dictionary, making it empty.
Syntax : dictionary.clear()
student = {'name': 'Ravi', 'age': 21, 'grade': 'A'}
student.clear()
print(student)
Returns a shallow copy of the dictionary β a new dictionary with the same key-value pairs, but not the same reference.
Syntax : new_dict = original_dict.copy()
student = {'name': 'Ravi', 'age': 21}
new_student = student.copy()
print(new_student)
# Modifying the copy does not affect the original
new_student['age'] = 30
print(student)
print(new_student)
Creates a new dictionary from a sequence of keys, each assigned the same value.
Syntax : dict.fromkeys(keys, value)
# Using a list of keys
keys = ['name', 'age', 'grade']
default_dict = dict.fromkeys(keys)
# Using a list of keys without specifying a value
keys = ['name', 'age', 'grade']
default_dict = dict.fromkeys(keys, 'Not Available')
If the dictionary contains nested dictionaries, the nested parts still reference the original:
deepcopy() solves this by copying everything recursively, so changes in the copied dictionary donβt affect the original at all.
Syntax : from copy import deepcopy
Syntax : new_dict = deepcopy(original_dict)
# Shallow Copy
d1 = {'info': {'age': 21}}
d2 = d1.copy()
d2['info']['age'] = 30
print(d1) # {'info': {'age': 30}} β Changed!
# deepcopy
from copy import deepcopy
original = {
'name': 'Ravi',
'marks': {'math': 90, 'science': 85}
}
copied = deepcopy(original)
# Change the nested dictionary
copied['marks']['math'] = 100
print(original)
# Output: {'name': 'Ravi', 'marks': {'math': 90, 'science': 85}}
print(copied)
# Output: {'name': 'Ravi', 'marks': {'math': 100, 'science': 85}}