KZulfazriawan
KZulfazriawan

Reputation: 62

Get dictionary contains in list if key and value exists

How to get complete dictionary data inside lists. but first I need to check them if key and value is exists and paired.

test = [{'a': 'hello'  , 'b': 'world', 'c': 1},
        {'a': 'crawler', 'b': 'space', 'c': 5},
        {'a': 'jhon'   , 'b': 'doe'  , 'c': 8}]

when I try to make it conditional like this

if any((d['c'] is 8) for d in test):

the value is True or False, But I want the result be an dictionary like

{'a': 'jhon', 'b': 'doe', 'c': 8}

same as if I do

if any((d['a'] is 'crawler') for d in test):

the results is:

{'a': 'crawler', 'b': 'space', 'c': 5}

Thanks in advance

Upvotes: 2

Views: 1127

Answers (2)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52133

is tests for identity, not for equality which means it compares the memory address not the values those variables are storing. So it is very likely it might return False for same values. You should use == instead to check for equality.

As for your question, you can use filter or list comprehensions over any:

>>> [dct for dct in data if dct["a"] == "crawler"]
>>> filter(lambda dct: dct["a"] == "crawler", data)

The result is a list containing the matched dictionaries. You can get the [0]th element if you think it contains only one item.

Upvotes: 3

LycuiD
LycuiD

Reputation: 2575

Use comprehension:

data = [{'a': 'hello'  , 'b': 'world', 'c': 1},
        {'a': 'crawler', 'b': 'space', 'c': 5},
        {'a': 'jhon'   , 'b': 'doe'  , 'c': 8}]

print([d for d in data if d["c"] == 8])
# [{'c': 8, 'a': 'jhon', 'b': 'doe'}]

Upvotes: 2

Related Questions