A dictionary is one of Python’s built-in data types that can store a mutable, unordered collection of items. Each item is stored as a key-value pair. Keys must be unique, and they can be strings, numbers, or tuples. Values, on the other hand, can be of any data type.
Dictionaries are created by placing a comma-separated list of key-value pairs inside curly braces {}
, where the key and value are separated by a colon :
.
person = {
"name": "John",
"age": 30,
"city": "New York"
}
To access a dictionary value, you can use the corresponding key inside square brackets []
.
print(person["name"]) # Outputs: John
Using the get()
method, you can also retrieve a value:
print(person.get("age")) # Outputs: 30
person["job"] = "Engineer"
person["city"] = "San Francisco"
del
keyword or the pop()
method.del person["age"]
# OR
person.pop("age")
person.clear()
print(person.keys()) # Outputs: dict_keys(['name', 'city', 'job'])
print(person.values()) # Outputs: dict_values(['John', 'San Francisco', 'Engineer'])
print(person.items()) # Outputs: dict_items([('name', 'John'), ('city', 'San Francisco'), ('job', 'Engineer')])
new_person = person.copy()
person_info = {"gender": "male", "city": "Los Angeles"}
person.update(person_info)
You can loop through a dictionary by using its keys, values, or key-value pairs.
# Loop through keys
for key in person:
print(key)
# Loop through values
for value in person.values():
print(value)
# Loop through key-value pairs
for key, value in person.items():
print(key, value)
Similar to list comprehensions, dictionary comprehensions provide a concise way to create dictionaries.
squared_numbers = {x: x**2 for x in (1, 2, 3, 4)}
print(squared_numbers) # Outputs: {1: 1, 2: 4, 3: 9, 4: 16}
Dictionaries in Python provide a valuable tool for organizing and managing data. Their flexibility and efficiency in accessing data (thanks to their hash-based implementation) make them suitable for a wide range of programming tasks. Whether you’re handling configurations, counting word frequencies, or managing user data, Python’s dictionaries offer a robust and intuitive way to get the job done.