Python Dictionaries: Key-Value Pairs
Dictionaries in Python are used to store data in key-value pairs. They are unordered, mutable, and do not allow duplicate keys.
**Creating Dictionaries**
Dictionaries are defined using curly braces `{}` with key-value pairs separated by commas:
person = {“name”: “Alice”, “age”: 30}
scores = {“math”: 95, “science”: 89}
**Accessing Dictionary Items**
You can access values by their keys:
print(person[“name”]) # Output: “Alice”
**Modifying Dictionaries**
You can add or change items using the key:
person[“age”] = 31
person[“city”] = “New York”
print(person)
**Dictionary Methods**
Python dictionaries come with several useful methods:
– `keys()`: Returns a view object displaying a list of all the keys.
– `values()`: Returns a view object displaying a list of all the values.
– `items()`: Returns a view object displaying a list of all key-value pairs.
**Example**:
print(person.keys()) # Output: dict_keys([“name”, “age”, “city”])
print(person.items()) # Output: dict_items([(“name”, “Alice”), (“age”, 31), (“city”, “New York”)])
**Conclusion**
Dictionaries are powerful for managing data where relationships between items are important. They offer efficient access to values via keys.