Andrey Andrey
Andrey Andrey

Reputation: 107

how to get values from dictionary filtered by condition

Good day everyone!

please help me to tackle the following issue.

I have some dictionary

d = {'key1': (0, 1), 'key2': (0, 0), 'key3': (4, 7), 'key4': (0, 0), 'key5': (9, 12), 'key2': (9, 12)}

I'm trying to extract key/value pars that have values of (0, 0)

newDict = dict()
for (k, v) in d.values():
    if v == 0:
        newDict[k] = v
newDict

but it doesn't works...

Upvotes: 0

Views: 64

Answers (2)

deadshot
deadshot

Reputation: 9061

Using dict.fromkeys()

res = dict.fromkeys((k for k, v in d.items() if v == (0, 0)), (0, 0))
print(res)

Output:

{'key2': (0, 0), 'key4': (0, 0)}

Upvotes: 1

Nick
Nick

Reputation: 147196

You need to compare both elements in the tuple, so v == (0, 0). You can simplify your code to use a dictionary comprehension:

d = {'key1': (0, 1), 'key2': (0, 0), 'key3': (4, 7), 'key4': (0, 0), 'key5': (9, 12), 'key6': (9, 12)}

newDict = { k : v for k, v in d.items() if v == (0, 0) }
print(newDict)

Output:

{'key2': (0, 0), 'key4': (0, 0)}

Note I've corrected the duplicate key in your dictionary by changing the second key2 to key6

Upvotes: 1

Related Questions