Topic 3: Dictionaries: Key-Value Pairs

1. Introduction

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.

2. Creating Dictionaries

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 :.

python
person = { "name": "John", "age": 30, "city": "New York" }

3. Accessing Values

To access a dictionary value, you can use the corresponding key inside square brackets [].

python
print(person["name"]) # Outputs: John

Using the get() method, you can also retrieve a value:

python
print(person.get("age")) # Outputs: 30

4. Modifying Dictionaries

  • Adding Items: You can add a new key-value pair.
python
person["job"] = "Engineer"
  • Updating Items: Simply assign a new value to an existing key.
python
person["city"] = "San Francisco"
  • Deleting Items: Use the del keyword or the pop() method.
python
del person["age"] # OR person.pop("age")
  • Clearing the Dictionary: This removes all items.
python
person.clear()

5. Dictionary Methods

  • keys(): Returns a list of all the dictionary keys.
python
print(person.keys()) # Outputs: dict_keys(['name', 'city', 'job'])
  • values(): Returns a list of all the dictionary values.
python
print(person.values()) # Outputs: dict_values(['John', 'San Francisco', 'Engineer'])
  • items(): Returns a list of all the dictionary’s key-value tuple pairs.
python
print(person.items()) # Outputs: dict_items([('name', 'John'), ('city', 'San Francisco'), ('job', 'Engineer')])
  • copy(): Returns a shallow copy of the dictionary.
python
new_person = person.copy()
  • update(): Takes another dictionary as an argument and updates the dictionary with elements from the other dictionary.
python
person_info = {"gender": "male", "city": "Los Angeles"} person.update(person_info)

6. Iterating Through Dictionaries

You can loop through a dictionary by using its keys, values, or key-value pairs.

python
# 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)

7. Dictionary Comprehensions

Similar to list comprehensions, dictionary comprehensions provide a concise way to create dictionaries.

python
squared_numbers = {x: x**2 for x in (1, 2, 3, 4)} print(squared_numbers) # Outputs: {1: 1, 2: 4, 3: 9, 4: 16}

8. Conclusion

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.