In this article we will discuss different ways to filter contents from a dictionary by conditions on keys or value or on both.

Suppose we have a dictionary in which int type element is key and string type elements are value i.e.

dictOfNames = {
   7 : 'sam',
   8: 'john',
   9: 'mathew',
   10: 'riti',
   11 : 'aadi',
   12 : 'sachin'
}

Now let’s discuss different ways to filter the contents of this dictionary arbitrary conditions,

Filter a Dictionary by conditions by creating a Generic function

Filter a Dictionary by keys in Python

Suppose we want to filter above dictionary by keeping only elements whose keys are even. For that we can just iterate over all the items of
dictionary and add elements with even key to an another dictionary i.e.

newDict = dict()
# Iterate over all the items in dictionary and filter items which has even keys
for (key, value) in dictOfNames.items():
   # Check if key is even then add pair to new dictionary
   if key % 2 == 0:
       newDict[key] = value

print('Filtered Dictionary : ')
print(newDict)

Output:
Filtered Dictionary : 
{8: 'john', 10: 'riti', 12: 'sachin'}

The filtered dictionary i.e. newDict now contains filtered elements from the original dictionary i.e. elements whose key is divisible by 2. Similarly we can have conditional filtering based on value field instead of key. But instead of writing code for iteration and condition checking again and again, we move the code to a generic function and pass condition from outside i.e.
'''
Iterate over all the key value pairs in dictionary and call the given
callback function() on each pair. Items for which callback() returns True,
add them to the new dictionary. In the end return the new dictionary.
'''
def filterTheDict(dictObj, callback):
    newDict = dict()
    # Iterate over all the items in dictionary
    for (key, value) in dictObj.items():
        # Check if item satisfies the given condition then add to new dict
        if callback((key, value)):
            newDict[key] = value
    return newDict

This function accepts,

  • A dictionary
  • A function that accepts a key/value pair and returns True or False

This function iterate over all the key value pairs in dictionary and call the given callback function() on each pair. Items for which callback() function returns True are added to the new dictionary. In the end new dictionary is returned.

Now let’s use this to filter a dictionary by key i.e.

# Filter a dictionary to keep elements only whose keys are even
newDict = filterTheDict(dictOfNames, lambda elem : elem[0] % 2 == 0)

print('Filtered Dictionary : ')
print(newDict)

Output:
Filtered Dictionary : 
{8: 'john', 10: 'riti', 12: 'sachin'}

Passed lambda function is used as condition while filtering contents inside function filterTheDict(). It returned a new dictionary which contains elements with even keys only.

Filter a Dictionary by values in Python

Let’s use the same filterTheDict() function created above to filter the dictionary. Suppose we want to keep the elements only in dictionary whose value field contains a string of length 6. To do that let’s pass the different lambda function to filterTheDict() i.e.

# Filter a dictionary to keep elements only whose values are string of length 6
newDict = filterTheDict(dictOfNames, lambda elem: len(elem[1]) == 6)

Output:
Filtered Dictionary : 
{9: 'mathew', 12: 'sachin'}

Passed lambda function to filterTheDict() in which we are checking condition on value field only. It returned a new dictionary which contains elements whose value is string of length 6.

Filter a Dictionary by filter()

Instead of creating our own function we can also use python’s filter() function too.

filter() function accepts a,

  • an iterable sequence to be filtered
  • a function that accepts an argument and returns bool i.e. True or False based on it’s logic

Returns:

  • A new sequence of filtered contents.

We need to convert this returned sequence to dict again. Let’s use filter() to do conditional filtering on dictionary.
Our original dictionary is,

dictOfNames = {
   7 : 'sam',
   8: 'john',
   9: 'mathew',
   10: 'riti',
   11 : 'aadi',
   12 : 'sachin'
}

Filter a Dictionary by keys in Python using filter()

Let’s filter items in dictionary whose keys are even i.e. divisible by 2,

# Filter dictionary by keeping elements whose keys are divisible by 2
newDict = dict(filter(lambda elem: elem[0] % 2 == 0, dictOfNames.items()))

print('Filtered Dictionary : ')
print(newDict)

Output:
Filtered Dictionary : 
{8: 'john', 10: 'riti', 12: 'sachin'}

Filter a Dictionary by values in Python using filter()

Let’s filter items in dictionary whose values are string of length 6,

# Filter dictionary by keeping elements whose values are string of length 6
newDict = dict(filter(lambda elem: len(elem[1]) == 6,dictOfNames.items()))

print('Filtered Dictionary : ')
print(newDict)

Output:
Filtered Dictionary : 
{9: 'mathew', 12: 'sachin'}

filter() function iterates above all the elements in passed dict and filter elements based on condition passed as callback.

Filter a Dictionary by Dict Comprehension

Our original dictionary is,

dictOfNames = {
   7 : 'sam',
   8: 'john',
   9: 'mathew',
   10: 'riti',
   11 : 'aadi',
   12 : 'sachin'
}

Filter a Dictionary by keys in Python using dict comprehension

Let’s filter items in dictionary whose keys are even i.e. divisible by 2 using dict comprehension ,

# Filter dictionary by keeping elements whose keys are divisible by 2
newDict = { key:value for (key,value) in dictOfNames.items() if key % 2 == 0}

print('Filtered Dictionary : ')
print(newDict)

Output:
Filtered Dictionary : 
{8: 'john', 10: 'riti', 12: 'sachin'}

Filter a Dictionary by values in Python using dict comprehension

Let’s filter items in dictionary whose values are string of length 6 by using dict comprehension,

# Filter dictionary by keeping elements whose values are string of length 6
newDict = {key: value for (key, value) in dictOfNames.items() if len(value) == 6 }

print('Filtered Dictionary : ')
print(newDict)

Output:
Filtered Dictionary : 
{9: 'mathew', 12: 'sachin'}

It iterates above all the elements in passed dict and filter elements based on condition passed as callback.

Python Dictionary Tutorial - Series:

  1. What is a Dictionary in Python & why do we need it?
  2. Creating Dictionaries in Python
  3. Iterating over dictionaries
  4. Check if a key exists in dictionary
  5. Check if a value exists in dictionary
  6. Get all the keys in Dictionary
  7. Get all the Values in a Dictionary
  8. Remove a key from Dictionary
  9. Add key/value pairs in Dictionary
  10. Find keys by value in Dictionary
  11. Filter a dictionary by conditions
  12. Print dictionary line by line
  13. Convert a list to dictionary
  14. Sort a Dictionary by key
  15. Sort a dictionary by value in descending or ascending order
  16. Dictionary: Shallow vs Deep Copy
  17. Remove keys while Iterating
  18. Get all keys with maximum value
  19. Merge two or more dictionaries in python

Subscribe with us to join a list of 2000+ programmers and get latest tips & tutorials at your inbox through our weekly newsletter.

Complete example is as follows,

'''
Iterate over all the key value pairs in dictionary and call the given
callback function() on each pair. Items for which callback() returns True,
add them to the new dictionary. In the end return the new dictionary.
'''
def filterTheDict(dictObj, callback):
    newDict = dict()
    # Iterate over all the items in dictionary
    for (key, value) in dictObj.items():
        # Check if item satisfies the given condition then add to new dict
        if callback((key, value)):
            newDict[key] = value
    return newDict

def main():

    dictOfNames = {
       7 : 'sam',
       8: 'john',
       9: 'mathew',
       10: 'riti',
       11 : 'aadi',
       12 : 'sachin'
    }

    print('Original Dictionary : ')
    print(dictOfNames)

    print('*** Filter a Dictionary by conditions by Iterating over elements ***')

    print('Filter a Dictionary by conditions on keys')

    newDict = dict()
    # Iterate over all the items in dictionary and filter items which has even keys
    for (key, value) in dictOfNames.items():
       # Check if key is even then add pair to new dictionary
       if key % 2 == 0:
           newDict[key] = value

    print('Filtered Dictionary : ')
    print(newDict)

    # Filter a dictionary to keep elements only whose keys are even
    newDict = filterTheDict(dictOfNames, lambda elem : elem[0] % 2 == 0)

    print('Filtered Dictionary : ')
    print(newDict)

    # Filter a dictionary to keep elements only whose values are string of length 6
    newDict = filterTheDict(dictOfNames, lambda elem: len(elem[1]) == 6)

    print('Filtered Dictionary : ')
    print(newDict)

    print('*** Filter a Dictionary by filter()***')

    # Filter dictionary by keeping elements whose keys are divisible by 2
    newDict = dict(filter(lambda elem: elem[0] % 2 == 0, dictOfNames.items()))

    print('Filtered Dictionary : ')
    print(newDict)

    # Filter dictionary by keeping elements whose values are string of length 6
    newDict = dict(filter(lambda elem: len(elem[1]) == 6,dictOfNames.items()))

    print('Filtered Dictionary : ')
    print(newDict)

    print('*** Filter a Dictionary by Dict Comprehension ***')

    # Filter dictionary by keeping elements whose keys are divisible by 2
    newDict = { key:value for (key,value) in dictOfNames.items() if key % 2 == 0}

    print('Filtered Dictionary : ')
    print(newDict)

    # Filter dictionary by keeping elements whose values are string of length 6
    newDict = {key: value for (key, value) in dictOfNames.items() if len(value) == 6 }

    print('Filtered Dictionary : ')
    print(newDict)


if __name__ == '__main__':
  main()

Output:
Original Dictionary : 
{7: 'sam', 8: 'john', 9: 'mathew', 10: 'riti', 11: 'aadi', 12: 'sachin'}
*** Filter a Dictionary by conditions by Iterating over elements ***
Filter a Dictionary by conditions on keys
Filtered Dictionary : 
{8: 'john', 10: 'riti', 12: 'sachin'}
Filtered Dictionary : 
{8: 'john', 10: 'riti', 12: 'sachin'}
Filtered Dictionary : 
{9: 'mathew', 12: 'sachin'}
*** Filter a Dictionary by filter()***
Filtered Dictionary : 
{8: 'john', 10: 'riti', 12: 'sachin'}
Filtered Dictionary : 
{9: 'mathew', 12: 'sachin'}
*** Filter a Dictionary by Dict Comprehension ***
Filtered Dictionary : 
{8: 'john', 10: 'riti', 12: 'sachin'}
Filtered Dictionary : 
{9: 'mathew', 12: 'sachin'}

 

Join a list of 2000+ Programmers for latest Tips & Tutorials