Dictionaries are Python's built-in mapping type.
They store data in `key:
valuepairs, where each key is unique and maps to a specific value. Dictionaries are unordered (in Python versions before 3.7, ordered in 3.7+ by insertion), mutable, and optimized for retrieving values when the key is known. They are defined by enclosing elements in curly braces{}`.
Creating Dictionaries
python# An empty dictionary empty_dict = {} # A dictionary of programming languages and their years of creation programming_languages = { "Python": 1991, "Java": 1995, "C++": 1985, "JavaScript": 1995 } # A dictionary with mixed key/value types mixed_dict = { "name": "Alice", "age": 30, "is_student": True, 1: "one" } print(empty_dict) print(programming_languages) print(mixed_dict) print(type(programming_languages)) # Output: <class 'dict'>
Key Rules:
- Keys must be unique: If you assign a new value to an existing key, the old value is overwritten.
- Keys must be immutable: Keys can be strings, numbers, or tuples. Lists and other mutable types cannot be used as keys.
- Values can be of any data type and can be duplicates.
Accessing Dictionary Values
You access values by referencing their corresponding key using square brackets [] or the get() method.
**1.
Using [] (Square Brackets):
**
pythonprint(programming_languages["Python"]) # Output: 1991 # print(programming_languages["Ruby"]) # This would raise a KeyError if 'Ruby' doesn't exist
2. Using dict.get(key, default_value):
The get() method is safer as it returns None (or a specified default_value) if the key is not found, instead of raising an error.
pythonprint(programming_languages.get("Java")) # Output: 1995 print(programming_languages.get("Ruby")) # Output: None print(programming_languages.get("Ruby", 2000)) # Output: 2000 (default value if key not found)
Modifying Dictionaries
Dictionaries are mutable, allowing you to add, change, or remove key-value pairs.
**1.
Adding new key-value pairs:
**
pythonprogramming_languages["Go"] = 2009 print(programming_languages) # Output: {'Python': 1991, 'Java': 1995, 'C++': 1985, 'JavaScript': 1995, 'Go': 2009}
**2.
Modifying an existing value:
**
pythonprogramming_languages["Java"] = 1996 # Update Java's year print(programming_languages) # Output: {'Python': 1991, 'Java': 1996, ...}
**3.
Removing key-value pairs:
**
del dict[key]: Removes the item with the specified key.dict.pop(key, default_value): Removes the item with the specified key and returns its value. Can provide a default if key not found.dict.clear(): Removes all items from the dictionary.
pythondel programming_languages["C++"] print(programming_languages) # Output: {'Python': 1991, 'Java': 1996, 'JavaScript': 1995, 'Go': 2009} popped_value = programming_languages.pop("Go") print(f"Popped value: {popped_value}, Dict now: {programming_languages}") # Output: Popped value: 2009, Dict now: {'Python': 1991, 'Java': 1996, 'JavaScript': 1995} programming_languages.clear() print(programming_languages) # Output: {}
Iterating Through Dictionaries
Dictionaries can be iterated in several ways:
- Looping through keys (default):
python
person = {"name": "Jane Doe", "age": 28, "city": "London"} for key in person: print(key) # Output: name, age, city dict.keys(): Returns a view object of all keys.pythonfor key in person.keys(): print(key)dict.values(): Returns a view object of all values.pythonfor value in person.values(): print(value) # Output: Jane Doe, 28, Londondict.items(): Returns a view object of all key-value pairs as tuples.pythonfor key, value in person.items(): print(f"{key}: {value}") # Output: # name: Jane Doe # age: 28 # city: London
Dictionaries are essential for representing structured data, such as records or configurations, where you need to associate unique identifiers (keys) with specific pieces of information (values).
Key Takeaways:
- Dictionaries store data as
key: valuepairs, defined with{}. - Keys must be unique and immutable; values can be any type.
- Access values using
dict[key](raisesKeyErrorif not found) ordict.get(key, default)(safer). - Modify by assigning to an existing key, add by assigning to a new key.
- Remove items with
del dict[key],dict.pop(key), ordict.clear(). - Iterate over keys (default),
keys(),values(), oritems()for key-value pairs.