Python - Filter odd elements from value lists in dictionary

Python dictionaries store key-value pairs where values can be lists. Filtering odd elements from these lists is a common task in data processing. An odd number is any integer that gives a remainder when divided by 2 (x % 2 != 0).

For example ?

Given dictionary: {'A': [10, 21, 22, 19], 'B': [2, 5, 8]}

After filtering odd elements: {'A': [21, 19], 'B': [5]}

Understanding Odd Number Detection

To identify odd numbers, we use the modulo operator ?

# Two ways to check for odd numbers
numbers = [1, 2, 3, 4, 5]

# Method 1: remainder not equal to 0
odds1 = [x for x in numbers if x % 2 != 0]
print("Using !=:", odds1)

# Method 2: remainder equals 1
odds2 = [x for x in numbers if x % 2 == 1]
print("Using ==:", odds2)
Using !=: [1, 3, 5]
Using ==: [1, 3, 5]

Using Dictionary Comprehension with List Comprehension

The most concise approach combines both comprehensions ?

def filter_odd_elements(data):
    return {key: [x for x in value if x % 2 != 0] for key, value in data.items()}

# Create sample dictionary
sample_dict = {
    'A': [2, 4, 16, 19, 17], 
    'B': [61, 71, 90, 80, 10], 
    'C': [11, 121, 13, 14, 15]
}

result = filter_odd_elements(sample_dict)
print("Filtered odd elements:")
for key, value in result.items():
    print(f"{key}: {value}")
Filtered odd elements:
A: [19, 17]
B: [61, 71]
C: [11, 121, 13, 15]

Using for Loop with filter() and lambda

This approach uses built-in functions for more explicit control ?

def filter_odd_with_filter(data):
    filtered_dict = {}
    for key, value in data.items():
        # Filter odd numbers using filter() and lambda
        odd_values = list(filter(lambda x: x % 2 != 0, value))
        filtered_dict[key] = odd_values
    return filtered_dict

# Test with sample data
test_dict = {
    'group1': [1, 2, 3, 4, 5], 
    'group2': [6, 7, 8, 9, 10], 
    'group3': [11, 12, 13, 14, 15]
}

result = filter_odd_with_filter(test_dict)
print("Using filter() method:")
print(result)
Using filter() method:
{'group1': [1, 3, 5], 'group2': [7, 9], 'group3': [11, 13, 15]}

Using for Loop with List Comprehension

This method combines explicit iteration with list comprehension ?

def filter_odds_explicit(data):
    result_dict = {}
    for key, value in data.items():
        # Use list comprehension for each list
        odd_numbers = [x for x in value if x % 2 != 0]
        result_dict[key] = odd_numbers
    return result_dict

# Test with different data
test_data = {
    'set_A': [307, 907, 100, 200], 
    'set_B': [110, 111, 120, 121], 
    'set_C': [50, 51, 52, 53]
}

filtered_result = filter_odds_explicit(test_data)
print("Explicit loop method:")
print(filtered_result)
Explicit loop method:
{'set_A': [307, 907], 'set_B': [111, 121], 'set_C': [51, 53]}

Performance Comparison

Method Readability Performance Best For
Dictionary + List Comprehension High Fastest Simple filtering
for Loop + filter() Medium Good Complex conditions
for Loop + List Comprehension High Good Step-by-step processing

Handling Empty Results

Sometimes filtering may result in empty lists ?

def filter_with_empty_check(data):
    return {key: [x for x in value if x % 2 != 0] for key, value in data.items()}

# Dictionary with some even-only lists
mixed_dict = {
    'evens': [2, 4, 6, 8], 
    'odds': [1, 3, 5, 7], 
    'mixed': [10, 11, 12, 13]
}

result = filter_with_empty_check(mixed_dict)
print("Results with empty lists:")
for key, value in result.items():
    if value:
        print(f"{key}: {value}")
    else:
        print(f"{key}: No odd numbers found")
Results with empty lists:
evens: No odd numbers found
odds: [1, 3, 5, 7]
mixed: [11, 13]

Conclusion

Dictionary and list comprehension provide the most concise solution for filtering odd elements. Use explicit loops when you need more control over the filtering process. All methods preserve the original dictionary structure while filtering values based on the odd number condition.

---
Updated on: 2026-03-27T08:10:32+05:30

975 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements