Chapter 18: Advanced Dictionary Functions in Python Programming


18.1 Introduction

Dictionaries are one of the most powerful and flexible data structures in Python. While basic operations such as adding, removing, or updating key-value pairs are commonly used, Python also provides several advanced dictionary functions and techniques that enhance the efficiency and expressiveness of your code. This chapter explores these advanced capabilities, providing you with the tools to write more optimized and elegant Python programs.


18.2 Dictionary Comprehensions

Dictionary comprehensions are a concise way to create dictionaries.

Syntax:

{key: value for key, value in iterable if condition}

Example:

squares = {x: x*x for x in range(6)}
print(squares)

Output:

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

18.3 The get() Method

The get() method is used to access a dictionary value by key with a default value if the key is not found.

person = {'name': 'Alice', 'age': 25}
print(person.get('age'))          # 25
print(person.get('gender', 'N/A'))  # N/A

18.4 The setdefault() Method

This method returns the value of a key if it is in the dictionary; otherwise, it inserts the key with a specified default value.

inventory = {'apple': 5}
inventory.setdefault('banana', 0)
print(inventory)

Output:

{'apple': 5, 'banana': 0}

18.5 Merging Dictionaries with | and update()

Using | Operator (Python 3.9+):

d1 = {'a': 1}
d2 = {'b': 2}
merged = d1 | d2
print(merged)

Using update():

d1.update(d2)
print(d1)

18.6 Using collections.defaultdict

defaultdict from the collections module provides a default value for nonexistent keys.

from collections import defaultdict

dd = defaultdict(int)
dd['a'] += 1
print(dd['a'])  # 1

Use Cases:

  • Counting frequencies

  • Grouping values


18.7 Using collections.OrderedDict

Maintains the insertion order of keys (prior to Python 3.7 where dict became ordered by default).

from collections import OrderedDict

od = OrderedDict()
od['one'] = 1
od['two'] = 2
print(od)

18.8 Using collections.ChainMap

Combines multiple dictionaries into a single view.

from collections import ChainMap

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
combined = ChainMap(dict1, dict2)
print(combined['b'])  # 2 (from dict1)

18.9 Dictionary Views: keys(), values(), items()

These return dynamic views of the dictionary’s keys, values, and items.

d = {'a': 1, 'b': 2}
print(d.keys())    # dict_keys(['a', 'b'])
print(d.values())  # dict_values([1, 2])
print(d.items())   # dict_items([('a', 1), ('b', 2)])

18.10 The pop() and popitem() Methods

  • pop(key): Removes the specified key.

  • popitem(): Removes and returns the last inserted key-value pair.

d = {'a': 1, 'b': 2}
d.pop('a')        # Removes 'a'
d.popitem()       # Removes the last item

18.11 Nested Dictionaries

A dictionary inside another dictionary.

employees = {
    'emp1': {'name': 'Alice', 'age': 25},
    'emp2': {'name': 'Bob', 'age': 30}
}
print(employees['emp1']['name'])  # Alice

18.12 Dictionary Sorting

Sort a dictionary by keys or values.

Sort by Keys:

d = {'b': 2, 'a': 1, 'c': 3}
print(dict(sorted(d.items())))

Sort by Values:

print(dict(sorted(d.items(), key=lambda item: item[1])))

18.13 Enumerate with Dictionaries

Though enumerate() works on iterables, it can be useful for indexed processing.

d = {'x': 10, 'y': 20}
for i, (k, v) in enumerate(d.items()):
    print(i, k, v)

18.14 Dictionary with zip() Function

Create a dictionary from two lists.

keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))
print(d)

18.15 Dictionary Filtering

Filter dictionary items using dictionary comprehension.

d = {'a': 1, 'b': 2, 'c': 3}
filtered = {k: v for k, v in d.items() if v > 1}
print(filtered)

18.16 Dictionary Flattening (Nested to Flat)

Flatten a nested dictionary using recursion.

def flatten(d, parent_key='', sep='_'):
    items = {}
    for k, v in d.items():
        new_key = parent_key + sep + k if parent_key else k
        if isinstance(v, dict):
            items.update(flatten(v, new_key, sep))
        else:
            items[new_key] = v
    return items

nested = {'a': {'b': {'c': 1}}}
print(flatten(nested))

Output:

{'a_b_c': 1}

18.17 Conclusion

Advanced dictionary functions allow for greater flexibility, performance, and clarity in code. Understanding how to use built-in methods like get(), setdefault(), or modules like collections can significantly enhance your programming capabilities. Whether you're performing data aggregation, filtering, or dynamic generation of content, dictionaries are central to efficient Python development.


18.18 Exercises

Q1. Create a dictionary from a list of words where each key is a word and its value is the length of the word.
Q2. Write a function that counts the frequency of each character in a string using defaultdict.
Q3. Merge two dictionaries and sort the result by value in descending order.
Q4. Use dictionary comprehension to create a dictionary of even numbers and their squares from 0 to 10.
Q5. Flatten a nested dictionary: {'a': 1, 'b': {'c': 2, 'd': {'e': 3}}}.

Comments