How to check for redundant combinations in a Python dictionary?

Python dictionaries are hashmaps where each key can only have one associated value. This prevents redundant key combinations by design. When you assign a new value to an existing key, it overwrites the previous value.

Basic Dictionary Behavior

Let's see what happens when we try to add a duplicate key ?

a = {'foo': 42, 'bar': 55}
print("Original dictionary:", a)

# Assigning new value to existing key
a['foo'] = 100
print("After reassignment:", a)
Original dictionary: {'foo': 42, 'bar': 55}
After reassignment: {'foo': 100, 'bar': 55}

Checking for Duplicate Keys During Creation

You can detect if you're trying to create redundant combinations by checking if a key already exists before adding it ?

data = {}
items = [('name', 'Alice'), ('age', 25), ('name', 'Bob')]

for key, value in items:
    if key in data:
        print(f"Warning: Key '{key}' already exists with value '{data[key]}'")
        print(f"Overwriting with new value '{value}'")
    data[key] = value

print("Final dictionary:", data)
Warning: Key 'name' already exists with value 'Alice'
Overwriting with new value 'Bob'
Final dictionary: {'name': 'Bob', 'age': 25}

Storing Multiple Values for Same Key

If you need multiple values for a single key, use a list as the value ?

from collections import defaultdict

# Using defaultdict to automatically create lists
multi_dict = defaultdict(list)
items = [('color', 'red'), ('color', 'blue'), ('size', 'large'), ('color', 'green')]

for key, value in items:
    multi_dict[key].append(value)

print(dict(multi_dict))
{'color': ['red', 'blue', 'green'], 'size': ['large']}

Manual Approach for Multiple Values

You can also manually handle multiple values without using defaultdict ?

data = {}
items = [('hobby', 'reading'), ('hobby', 'gaming'), ('city', 'NYC')]

for key, value in items:
    if key in data:
        if isinstance(data[key], list):
            data[key].append(value)
        else:
            data[key] = [data[key], value]
    else:
        data[key] = value

print(data)
{'hobby': ['reading', 'gaming'], 'city': 'NYC'}

Conclusion

Python dictionaries automatically prevent redundant key combinations by overwriting duplicate keys. Use lists as values or collections.defaultdict when you need to store multiple values for the same key.

Updated on: 2026-03-24T20:31:17+05:30

205 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements