Data Structures
Python Dictionaries: Part 5
Dictionaries are data structures that store key-value pairs, similar to hashmaps or associative arrays in other programming languages. The key acts as a unique identifier to access its corresponding value, much like looking up a word (key) to find its definition (value) in a physical dictionary.
Ryan McBride
Ryan McBride
alt

Source: Joshua Hoehne on Unsplash

1. Creating a Dictionary

Dictionaries are created using curly braces {}. Key-value pairs are added within the braces, separated by a colon :. Multiple key-value pairs are separated by commas ,.


        student = {
            "name": "John",
            "age": 25,
            "courses": ["math", "compy"]
        }
        print(student) # Output: {'name': 'John', 'age': 25, 'courses': ['math', 'compy']}
                

2. Accessing Values

Values can be accessed by using square brackets [] with the key inside. Keys can be strings or immutable data types like integers.


        name = student["name"]
        print(name) # Output: John

        courses = student["courses"]
        print(courses) # Output: ['math', 'compy']

        student_with_int_key = {
            1: "John",
            "age": 25
        }
        print(student_with_int_key) # Output: John
                

3. Handling Non-existent Keys

Trying to access a non-existent key using square brackets will result in a KeyError. The get() method can be used to avoid errors. It returns None by default if the key doesn't exist. You can also provide a default value as a second argument to the get() method.


        phone = student.get("phone")
        print(phone) # Output: None

        phone = student.get("phone", "not found")
        print(phone) # Output: not found
                

4. Adding and Updating Entries

New key-value pairs can be added by assigning a value to a new key using square brackets. If a key already exists, assigning a new value to it will update the existing value. The update() method can be used to add or update multiple key-value pairs at once by passing in another dictionary.


        student["phone"] = "555-5555"
        print(student) # Output: {'name': 'John', 'age': 25, 'courses': ['math', 'compy'], 'phone': '555-5555'}

        student["name"] = "Jane"
        print(student) # Output: {'name': 'Jane', 'age': 25, 'courses': ['math', 'compy'], 'phone': '555-5555'}

        student.update({"age": 26, "city": "New York"})
        print(student) # Output: {'name': 'Jane', 'age': 26, 'courses': ['math', 'compy'], 'phone': '555-5555', 'city': 'New York'}
                

5. Deleting Entries

The del keyword can be used to delete a specific key-value pair. The pop() method removes and returns the value of a specified key.


        del student["city"]
        print(student) # Output: {'name': 'Jane', 'age': 26, 'courses': ['math', 'compy'], 'phone': '555-5555'}

        removed_age = student.pop("age")
        print(student) # Output: {'name': 'Jane', 'courses': ['math', 'compy'], 'phone': '555-5555'}
        print(removed_age) # Output: 26
                

6. Looping Through Dictionaries

The len() function returns the number of key-value pairs in a dictionary. The keys() method returns a view object that displays a list of all the keys in the dictionary. The values() method returns a view object that displays a list of all the values in the dictionary. The items() method returns a view object that displays a list of dictionary's key-value tuple pairs. You can loop through the keys of a dictionary directly. To loop through both keys and values, you should use the items() method in the loop.


        print(len(student)) # Output: 3

        print(student.keys()) # Output: dict_keys(['name', 'courses', 'phone'])

        print(student.values()) # Output: dict_values(['Jane', ['math', 'compy'], '555-5555'])

        print(student.items()) # Output: dict_items([('name', 'Jane'), ('courses', ['math', 'compy']), ('phone', '555-5555')])

        for key in student:
            print(key)
        # Output:
        # name
        # courses
        # phone

        for key, value in student.items():
            print(f"Key: {key}, Value: {value}")
        # Output:
        # Key: name, Value: Jane
        # Key: courses, Value: ['math', 'compy']
        # Key: phone, Value: 555-5555