In Python, a dictionary is a data structure that stores data in key-value pairs.
Dictionaries are
mutable, unordered, and indexed by keys, which are unique and can be of any hashable type
(typically strings or numbers). The values associated with keys can be of any type.
Creating a Dictionary
we can create a dictionary by using curly braces {} or by using the dict() constructor.
# Creating a dictionary with curly braces
person = {
"name": "John",
"age": 30,
"city": "New York"
# Creating a dictionary using dict()
person2 = dict(name="Alice", age=25, city="Los Angeles")
Accessing Dictionary Values
To access values in a dictionary, we use the key inside square brackets [] or the .get() method.
# Accessing with square brackets
print(person["name"]) # Output: John
# Accessing with the get() method (prevents KeyError if key doesn't exist)
print(person.get("age")) # Output: 30
print(person.get("gender", "Not specified")) # Output: Not specified (default value)
Adding or Updating Values
we can add a new key-value pair or update an existing key's value.
# Adding a new key-value pair
person["gender"] = "Male"
# Updating an existing key's value
person["age"] = 31
Removing Elements
There are several ways to remove elements from a dictionary:
pop(key) removes the item with the specified key and returns its value.
popitem() removes and returns the last inserted item (useful for Python 3.7+ where
dictionaries preserve insertion order).
del removes the item with the specified key.
clear() removes all items from the dictionary.
# Using pop() to remove a key
age = person.pop("age") # Removes "age" and returns its value
print(age) # Output: 31
# Using del to remove a key
del person["city"]
# Using clear() to empty the dictionary
person.clear() # Removes all items
Looping Through a Dictionary
You can loop through a dictionary in several ways:
Looping through the keys.
Looping through the values.
Looping through both keys and values.
# Loop through keys
for key in person:
print(key)
# Loop through values
for value in person.values():
print(value)
# Loop through both keys and values
for key, value in person.items():
print(f"{key}: {value}")
Dictionary Methods
keys() returns a list of all the keys.
values() returns a list of all the values.
items() returns a list of key-value pairs as tuples.
update() merges another dictionary into the current one.
Python dictionaries are powerful and flexible, allowing you to store and manipulate data efficiently
using key-value pairs. Common operations include accessing, adding, updating, and removing
elements, as well as looping through the dictionary.
Build in methods in dictonaries
Python dictionaries come with a variety of built-in methods to manipulate and interact with the data
they store. Below is a list of commonly used dictionary methods in Python, along with examples for
each.
1. dict.clear()
Removes all elements from the dictionary, leaving it empty.
person = {"name": "John", "age": 30, "city": "New York"}
person.clear()
print(person) # Output: {}
2. dict.copy()
Returns a shallow copy of the dictionary.
person = {"name": "John", "age": 30, "city": "New York"}
person_copy = person.copy()
print(person_copy) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
3. dict.get(key[, default])
Returns the value for the specified key. If the key does not exist, returns the optional default value
(or None if no default is provided).
person = {"name": "John", "age": 30}
print(person.get("age")) # Output: 30
print(person.get("gender", "N/A")) # Output: N/A
4. dict.items()
Returns a view object that displays a list of dictionary's key-value tuple pairs.
person = {"name": "John", "age": 30}
print(person.items()) # Output: dict_items([('name', 'John'), ('age', 30)])
5. dict.keys()
Returns a view object that displays a list of all the dictionary’s keys.
person = {"name": "John", "age": 30}
print(person.keys()) # Output: dict_keys(['name', 'age'])
6. dict.values()
Returns a view object that displays a list of all the dictionary’s values.
person = {"name": "John", "age": 30}
print(person.values()) # Output: dict_values(['John', 30])
7. dict.pop(key[, default])
Removes and returns the value for the specified key. If the key is not found, it returns the optional
default value (or raises a KeyError if no default is provided).
person = {"name": "John", "age": 30}
age = person.pop("age")
print(age) # Output: 30
print(person) # Output: {'name': 'John'}
9. dict.setdefault(key[, default])
If the key exists, it returns its value. If the key doesn’t exist, it inserts the key with the provided
default value and returns the default.
person = {"name": "John"}
age = person.setdefault("age", 25)
print(age) # Output: 25
print(person) # Output: {'name': 'John', 'age': 25}
10. dict.update([other])
Updates the dictionary with elements from another dictionary or iterable of key-value pairs. Existing
keys will be updated, and new ones will be added.
person = {"name": "John", "age": 30}
person.update({"city": "New York", "age": 31})
print(person) # Output: {'name': 'John', 'age': 31, 'city': 'New York'}
11. dict.fromkeys(keys[, value])
Creates a new dictionary from the given sequence of keys, with all values set to the specified value
(or None if no value is provided).
keys = ["name", "age", "city"]
new_dict = dict.fromkeys(keys, "Unknown")
print(new_dict) # Output: {'name': 'Unknown', 'age': 'Unknown', 'city': 'Unknown'}