Python Dictionaries
Learning Python Day 8
In Python, dictionaries are unordered collections of key-value pairs. They are incredibly useful for storing data efficiently
Creating Dictionary
You can create a dictionary by enclosing comma-separated key-value pairs within curly braces {}
or by using the dict()
constructor.
# Creating a dictionary using curly braces
person = {'name': 'John', 'age': 30, 'city': 'New York'}
# Creating a dictionary using dict() constructor
person = dict(name = John, age = 30, city = New York')
Accessing Values
You can access the values in a dictionary by referring to their corresponding key using square brackets[]
. If the key doesn’t exist, it will raise a KeyError
. Alternatively, you can use the get()
method, which returns None
or a default value if the key is not found.
person = {'name': 'John', 'age': 30, 'city': 'New York'}
print(person['name']) # Output: John
print(person.get('age')) # Output: 30
print(person.get('gender', 'Unknown')) # Output: Unknown
Modifying Values
You can modify the value of a specific key in a dictionary by assigning a new value to it.
person = {'name': 'John', 'age': 30, 'city': 'New York'}
person['age'] = 35
print(person) # Output: {'name': 'John', 'age': 35, 'city': 'New York'}
Adding and Removing Key-Value Pairs
You can add new key-value pairs to a dictionary or remove existing ones using the update()
method, pop()
method, or the del
keyword.
person = {'name': 'John', 'age': 30, 'city': 'New York'}
# Adding a new key-value pair
person['gender'] = 'Male'
print(person) # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'gender': 'Male'}
# Removing a key-value pair using del
del person['age']
print(person) # Output: {'name': 'John', 'city': 'New York'}
# Removing a key-value pair using pop
removed_value = person.pop('city')
print(person) # Output: {'name': 'John'}
print(removed_value) # Output: New York
Checking Membership
You can check if a key exists in a dictionary by using the in
keyword.
person = {'name': 'John', 'age': 30, 'city': 'New York'}
print('name' in person) # Output: True
print('gender' in person) # Output: False
Iterating Over a Dicitonary
You can iterate over the keys, values, or both using various methods like keys()
, values()
, and items()
.
person = {'name': 'John', 'age': 30, 'city': 'New York'}
# Iterating over keys
for key in person.keys():
print(key) # Output: name, age, city
# Iterating over values
for value in person.values():
print(value) # Output: John, 30, New York
# Iterating over key-value pairs
for key, value in person.items():
print(key, value) # Output: name John, age 30, city New York