Dictionary
A dictionary in Python is a built-in data type that allows you to store data in key-value pairs.
Unlike lists or tuples, which use indexes to access elements, dictionaries use keys. This makes
them ideal for situations where you need to associate values with specific identifiers (keys),
rather than just using a sequential index.
Basic syntax:
my_dict = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Features of Dictionaries:
1. Unordered:
○ In Python versions prior to 3.7, dictionaries are unordered collections. In Python
3.7+, dictionaries are guaranteed to maintain insertion order (the order in which
the items were added).
2. Mutable:
○ Dictionaries are mutable, meaning that you can change, add, or remove key-value
pairs after the dictionary is created.
3. Indexed by Keys:
○ Unlike lists, dictionaries are indexed by keys, not integers. The keys must be of an
immutable type, such as strings, numbers, or tuples.
4. No Duplicate Keys:
○ Each key in a dictionary must be unique. If you try to insert a duplicate key, the
new value will overwrite the existing value for that key
Example
# Creating a dictionary
my_dict = {
"name": "John",
"age": 30,
"city": "New York"}
# Accessing values using keys
print(my_dict["name"]) # Output: John
print(my_dict["age"]) # Output: 30
Built-in Dictionary Methods:
clear():
○ Removes all items from the dictionary.
[Link]()
copy():
○ Returns a shallow copy of the dictionary.
new_person = [Link]()
fromkeys():
○ Creates a new dictionary with the given keys and a default value.
keys = ["name", "age", "city"]
default_value = None
new_dict = [Link](keys, default_value)
get():
○ Returns the value of the specified key. If the key doesn't exist, it returns None
(or a default value).
[Link]("name") # Output: Alice
items():
○ Returns a view object that displays a list of a dictionary's key-value tuple pairs.
items = [Link]()
keys():
○ Returns a view object that displays a list of all the dictionary's keys.
keys = [Link]()
pop():
○ Removes the specified key and returns its corresponding value.
age = [Link]("age") # Removes 'age' and returns its value
popitem():
○ Removes and returns the last inserted key-value pair.
item = [Link]()
setdefault():
○ Returns the value of the specified key. If the key doesn't exist, it inserts the key
with a default value.
[Link]("email", "Condingninja@.com")
values():
Returns a view object that displays a list of all the dictionary's values.
values = [Link]()
Dictionary Operations:
Accessing Values:
○ You can access the value associated with a key using square brackets [] or the
get() method.
Using square brackets:
value = my_dict["name"]
Using the get() method:
value = my_dict.get("age")
The get() method is useful because it does not raise an error if the key does not exist,
unlike square bracket access. If the key is not found, it returns None (or a custom
default value if provided).
Adding or Updating Elements:
○ You can add new key-value pairs or update existing ones by assigning values to a
key.
my_dict["email"] = "john@[Link]" # Adding new key-value pair
my_dict["age"] = 35 # Updating existing key-value pair
Removing Elements:
○ You can remove key-value pairs using del, pop(), or popitem().
Using del:
del my_dict["city"]
Using pop(): (removes the specified key and returns its value)
value = my_dict.pop("age")
Using popitem(): (removes the last inserted key-value pair)
item = my_dict.popitem() # Returns the last item (key, value) tuple
Iterating Over a Dictionary:
○ You can loop through a dictionary to access its keys, values, or key-value pairs.
Iterating over keys:
t
for key in my_dict:
print(key)
Iterating over values:
for value in my_dict.values():
print(value)
Iterating over key-value pairs:
for key, value in my_dict.items():
print(key, value)
Checking if a Key Exists:
○ Use the in keyword to check if a key exists in the dictionary.
if "name" in my_dict:
print("Key 'name' exists")
Copying a Dictionary:
○ You can create a shallow copy of a dictionary using the copy() method.
new_dict = my_dict.copy()
Merging Dictionaries:
○ You can merge two dictionaries using the update() method or the | operator
(available in Python 3.9+).
Using update() method:
my_dict.update({"email": "Codingninja@.com”}
Using | operator (Python 3.9+):
new_dict = my_dict | {"email": "Codingninja@.com"}
Exercise 1: Merge Two Dictionaries
Task: Create two dictionaries:
1. dict1 with keys {"a": 1, "b": 2}
2. dict2 with keys {"c": 3, "d": 4}
Merge both dictionaries into one new dictionary.
Exercise 2: Create a Dictionary
Task: Create a dictionary called student_info that contains:
● The student's name as "name"
● The student's age as "age"
● The student's grade as "grade"
Print the dictionary.
Exercise 3: Adding or Updating Items
Task: Create a dictionary person with two keys: "name" and "age". Then, do the following:
1. Add a "city" key with your city as its value.
2. Update the "age" key to a new age.
Exercise 4: Loop Through Dictionary
Given the dictionary fruits_prices, loop through the dictionary and print the name of each fruit
and its corresponding price.
Exercise 5: Create a Nested Dictionary
Create a dictionary called contacts where each contact contains the name of the person and
their phone number. Each contact is a dictionary, and the dictionary contacts should have the
names as keys.