Skip to content

Python filter dictionary

  • by

You can filter the dictionary in different ways by conditions on keys or values or on both In Python. Just iterate over all the items of the dictionary and add elements with even keys to another dictionary i.e.

Python filter dictionary example

Simple example code filters a Dictionary by conditions by creating a Generic function. Let’s filter the given dictionary by keeping only elements whose keys are even.

dictOfNames = {
    1: 'Tim',
    2: 'John',
    3: 'Mike',
    4: 'Sam',
    5: 'Ryan',
    6: 'Kik'
}

newDict = dict()
# Iterate over all the items in dictionary
for (key, value) in dictOfNames.items():
    # Check if key is even then add
    if key % 2 == 0:
        newDict[key] = value
        
print('Filtered Dictionary : ')
print(newDict)

Output:

Python filter dictionary example

Filter a Dictionary by values

Let’s keep the elements only in the dictionary whose value field contains a string of length 6.

dictOfNames = {
    1: 'Tim K',
    2: 'John T',
    3: 'Mike O',
    4: 'Sam',
    5: 'Ryan',
    6: 'Kik'
}


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


newDict = filterTheDict(dictOfNames, lambda elem: len(elem[1]) == 6)

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

Output: {2: ‘John T’, 3: ‘Mike O’}

Python dictionary filter lambda

The Lambda function is defined without a name, that’s why it is also called an anonymous function.

new_Dict = {2: "Australia", 16: "Germany", 17: "Japan",1:"China"}
my_dict = dict(filter(lambda val: len(val[1]) == 5,new_Dict.items()))

print(my_dict)

Output: {17: ‘Japan’, 1: ‘China’}

Do comment if you have any doubts or suggestions on this Python filter topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading