Python 3 - Dictionary
Python 3 - Dictionaries
Section titled “Python 3 - Dictionaries”Dictionaries are a fundamental Python data structure used for storing collections of key-value pairs. Think of them like real-world dictionaries where you look up a word (the key) to find its definition (the value).
Syntax: Dictionaries are enclosed in curly braces {}. Each item consists of a key: value pair, separated by commas. An empty dictionary is {}.
# Example dictionarystudent = { "name": "Zara", "age": 7, "class": "First", "id": "S123"}
empty_dict = {}Key Characteristics:
- Keys must be unique within a dictionary.
- Keys must be of an immutable data type (like strings, numbers, or tuples containing only immutables). Lists or other dictionaries cannot be keys.
- Values can be of any data type (numbers, strings, lists, other dictionaries, etc.) and are not required to be unique.
- Order (Python 3.7+): Standard Python dictionaries preserve the order in which items were inserted. Before Python 3.7, dictionaries were unordered.
Accessing Values
Section titled “Accessing Values”You access the value associated with a key using square brackets []:
#!/usr/bin/env python3
student = { 'name': 'Zara', 'age': 7, 'class': 'First'}
print(f"Student's Name: {student['name']}")print(f"Student's Age: {student['age']}")Output:
Student's Name: ZaraStudent's Age: 7KeyError: If you try to access a key that doesn’t exist using square brackets, Python raises a KeyError.
#!/usr/bin/env python3
student = {'name': 'Zara', 'age': 7}# print(student['grade']) # This would cause a KeyErrorUsing .get() for Safer Access: The .get(key, default) method provides a safer way to access values. It returns the value if the key exists, or a specified default value (which is None if not provided) if the key is not found. This avoids KeyErrors.
#!/usr/bin/env python3
student = {'name': 'Zara', 'age': 7}
grade = student.get('grade') # Returns None as 'grade' key doesn't existprint(f"Student's Grade: {grade}")
grade_safe = student.get('grade', 'Not Available') # Returns 'Not Available'print(f"Student's Grade (safe): {grade_safe}")
name = student.get('name', 'Unknown') # Returns 'Zara' as 'name' existsprint(f"Student's Name (safe): {name}")Updating and Adding Items
Section titled “Updating and Adding Items”You can add new key-value pairs or update the value of an existing key using assignment with square brackets:
#!/usr/bin/env python3
student = { 'name': 'Zara', 'age': 7, 'class': 'First'}
# Update existing entrystudent['age'] = 8
# Add a new entrystudent['school'] = "Central Elementary"
print(f"Updated Age: {student['age']}")print(f"Added School: {student['school']}")print(f"Full updated dictionary: {student}")Output:
Updated Age: 8Added School: Central ElementaryFull updated dictionary: {'name': 'Zara', 'age': 8, 'class': 'First', 'school': 'Central Elementary'}Using update(): You can also merge another dictionary (or an iterable of key-value pairs) into an existing dictionary using the update() method. Existing keys will be overwritten.
#!/usr/bin/env python3
student = {'name': 'Zara', 'age': 8}new_info = {'age': 9, 'city': 'New York'}
student.update(new_info)print(f"Updated with new_info: {student}")Output:
Updated with new_info: {'name': 'Zara', 'age': 9, 'city': 'New York'}Deleting Items
Section titled “Deleting Items”There are several ways to remove items from a dictionary:
del dict[key]: Removes the item with the specified key. RaisesKeyErrorif the key doesn’t exist.dict.pop(key, [default]): Removes the item with the specified key and returns its value. RaisesKeyErrorif the key doesn’t exist and no default is provided.dict.popitem(): Removes and returns the last inserted (key, value) pair (in Python 3.7+). RaisesKeyErrorif the dictionary is empty.dict.clear(): Removes all items from the dictionary, making it empty.
#!/usr/bin/env python3
student = { 'name': 'Zara', 'age': 9, 'class': 'First', 'city': 'New York'}
# Using deldel student['city']print(f"After del 'city': {student}")
# Using popremoved_age = student.pop('age')print(f"Removed age using pop: {removed_age}")print(f"After pop 'age': {student}")
# Using popitem (removes the last added item: 'class')removed_item = student.popitem()print(f"Removed item using popitem: {removed_item}")print(f"After popitem: {student}")
# Using clearstudent.clear()print(f"After clear: {student}")
# Deleting the entire dictionary variablestudent_copy = {'a': 1}del student_copy# print(student_copy) # Raises NameError: name 'student_copy' is not definedDictionary Keys Requirements Recap
Section titled “Dictionary Keys Requirements Recap”Remember these two crucial points about dictionary keys:
- Uniqueness: Keys must be unique. If you assign a value to an existing key, the old value is replaced.
- Immutability: Keys must be of an immutable type (e.g., strings, numbers, tuples containing only immutable elements). You cannot use lists or other dictionaries as keys because they are mutable (can be changed in place).
#!/usr/bin/env python3
# Duplicate key example (last assignment wins)dict_dup = {'name': 'Zara', 'age': 7, 'name': 'Manni'}print(f"Duplicate key example: {dict_dup}") # Output: {'name': 'Manni', 'age': 7}
# Immutable key example (tuple as key)location_counts = {('New York', 'NY'): 150, ('Los Angeles', 'CA'): 200}print(f"Tuple as key: {location_counts[('New York', 'NY')]}")
# Attempting mutable key (list) - Raises TypeError# mutable_key_dict = {['user']: 'data'} # TypeError: unhashable type: 'list'Common Dictionary Methods and Operations
Section titled “Common Dictionary Methods and Operations”Python provides useful built-in functions and dictionary methods:
Built-in Functions:
len(dict): Returns the number of key-value pairs in the dictionary.str(dict): Returns a printable string representation of the dictionary.type(variable): Returns the type of the variable (e.g.,<class 'dict'>).
Dictionary Methods:
| Method | Description |
|---|---|
dict.clear() | Removes all items from the dictionary. |
dict.copy() | Returns a shallow copy of the dictionary. Changes to mutable values inside the copy might affect the original. |
dict.fromkeys(seq, [value]) | Creates a new dictionary with keys from seq and all values set to value (defaults to None). |
dict.get(key, [default]) | Returns the value for key if it exists, otherwise returns default (or None). Doesn’t raise KeyError. |
key in dict (Operation) | Returns True if key exists in the dictionary, False otherwise. (Replaces the old has_key method). |
dict.items() | Returns a view object displaying a list of a dictionary’s (key, value) tuple pairs. Changes to the dictionary are reflected in the view. |
dict.keys() | Returns a view object displaying a list of the dictionary’s keys. |
dict.values() | Returns a view object displaying a list of the dictionary’s values. |
dict.pop(key, [default]) | Removes the specified key and returns the corresponding value. If key is not found, default is returned if given, otherwise raises KeyError. |
dict.popitem() | Removes and returns the last inserted (key, value) pair as a tuple (Python 3.7+). Raises KeyError if empty. |
dict.setdefault(key, [default]) | If key is in the dictionary, returns its value. If not, inserts key with a value of default (or None) and returns default. |
dict.update(other_dict) | Updates the dictionary with the key-value pairs from other_dict, overwriting existing keys. |
Example using views:
#!/usr/bin/env python3
student = {'name': 'Zara', 'age': 9, 'class': 'First'}
keys_view = student.keys()values_view = student.values()items_view = student.items()
print(f"Keys: {keys_view}") # Output: dict_keys(['name', 'age', 'class'])print(f"Values: {values_view}") # Output: dict_values(['Zara', 9, 'First'])print(f"Items: {items_view}") # Output: dict_items([('name', 'Zara'), ('age', 9), ('class', 'First')])
# Views reflect changesstudent['id'] = 'S123'print(f"Keys after adding ID: {keys_view}")
# Convert view to list if neededkey_list = list(student.keys())print(f"Keys as list: {key_list}")