Creating Dictionaries
The simplest way to create a dictionary is using curly braces {}
and separating key-value pairs with colons :
. Keys must be immutable (like strings, numbers, or tuples), while values can be of any data type.
= {"name": "Alice", "age": 30, "city": "New York"}
my_dict print(my_dict) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}
= {} #creating an empty dictionary
empty_dict print(empty_dict) # Output: {}
#Using the dict() constructor
= dict(country = "USA", zipcode = 10001)
another_dict print(another_dict) # Output: {'country': 'USA', 'zipcode': 10001}
Accessing Values
Accessing values is done using the key within square brackets []
. Attempting to access a non-existent key raises a KeyError
.
= my_dict["name"]
name print(name) # Output: Alice
= my_dict.get("age")
age print(age) # Output: 30
= my_dict.get("state", "N/A") #If key not found return default value
city print(city) #Output: N/A
Adding and Modifying Entries
Adding new key-value pairs is straightforward:
"occupation"] = "Engineer"
my_dict[print(my_dict) # Output: {'name': 'Alice', 'age': 30, 'city': 'New York', 'occupation': 'Engineer'}
"age"] = 31 #Modify existing entry
my_dict[print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'city': 'New York', 'occupation': 'Engineer'}
Deleting Entries
Several methods exist for removing entries:
del my_dict["city"]
print(my_dict) # Output: {'name': 'Alice', 'age': 31, 'occupation': 'Engineer'}
= my_dict.pop("occupation") #Removes and returns the value associated with the key
popped_value print(popped_value) #Output: Engineer
print(my_dict) # Output: {'name': 'Alice', 'age': 31}
#Removes and returns an arbitrary key-value pair (last inserted in CPython)
my_dict.popitem() print(my_dict) #Output will vary based on insertion order, likely: {}
#Removes a key only if it is present in the dictionary
"name", "Bob") # No change since key exists
my_dict.setdefault(print(my_dict)
"country", "USA") # Key added since it doesn't exist
my_dict.setdefault(print(my_dict)
Iterating Through Dictionaries
You can iterate through keys, values, or both using loops:
for key in my_dict:
print(key)
for value in my_dict.values():
print(value)
for key, value in my_dict.items():
print(f"{key}: {value}")
Checking for Key Existence
Use the in
operator to efficiently check if a key exists:
if "name" in my_dict:
print("Key 'name' exists")
Dictionary Comprehension
Similar to list comprehensions, dictionary comprehensions provide a concise way to create dictionaries:
= {x: x**2 for x in range(1, 6)}
squares print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Methods for Dictionary Manipulation
Python offers a rich set of built-in methods for manipulating dictionaries, enhancing their flexibility and utility. Exploring these methods will allow for more complex dictionary operations. Further exploration of methods like update()
, clear()
, and others is highly recommended.