KZulfazriawan KZulfazriawan - 1 year ago 129
Python Question

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 before.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download