How can I check if key exists in list of dicts in python?

PythonPython 2.7

Python Problem Overview


Say I have a list of dicts that looks like this:

[{1: "a"}, {2: "b"}]

What is the pythonic way to indicate if a certain key is in one of the dicts in the list?

Python Solutions


Solution 1 - Python

I'd probably write:

>>> lod = [{1: "a"}, {2: "b"}]
>>> any(1 in d for d in lod)
True
>>> any(3 in d for d in lod)
False

although if there are going to be a lot of dicts in this list you might want to reconsider your data structure.

If you want the index and/or the dictionary where the first match is found, one approach is to use next and enumerate:

>>> next(i for i,d in enumerate(lod) if 1 in d)
0
>>> next(d for i,d in enumerate(lod) if 1 in d)
{1: 'a'}
>>> next((i,d) for i,d in enumerate(lod) if 1 in d)
(0, {1: 'a'})

This will raise StopIteration if it's not there:

>>> next(i for i,d in enumerate(lod) if 3 in d)
Traceback (most recent call last):
  File "<ipython-input-107-1f0737b2eae0>", line 1, in <module>
    next(i for i,d in enumerate(lod) if 3 in d)
StopIteration

If you want to avoid that, you can either catch the exception or pass next a default value like None:

>>> next((i for i,d in enumerate(lod) if 3 in d), None)
>>>

As noted in the comments by @drewk, if you want to get multiple indices returned in the case of multiple values, you can use a list comprehension:

>>> lod = [{1: "a"}, {2: "b"}, {2: "c"}]
>>> [i for i,d in enumerate(lod) if 2 in d]
[1, 2]

Solution 2 - Python

To see in single dictoray we use 'in' keyword:

key in dic_instance

To check in list of dictionary, iterate through dictionary list and use 'any' function, so if key found in any of the dictionary, it will not iterate the list further.

dic_list = [{1: "a"}, {2: "b"}]
any(2 in d for d in dic_list)
True
any(4 in d for d in dic_list)
False

Solution 3 - Python

Use any function with a generator:

>>> d = [{1: "a"}, {2: "b"}]
>>> any(1 in x for x in d)
True

any function returns True, if at least one element in the iterable passed to it is True. But you really need to consider, why are you not having all the key: value pairs in a single dict?

Solution 4 - Python

parsedData=[]
dataRow={}
if not any(d['url'] == dataRow['url'] for d in self.parsedData):
       self.parsedData.append(dataRow)

Solution 5 - Python

To search through deeply nested data structure I used this code to recursively look for keys in both lists and dictionaries

def isKey(dictORlist, key):
# dictORlist is the data structure you want to search
# key is the keyword you want to search for
def checkList(List, key):
    if isinstance(List, list):
        for i in List:
             return isKey(i, key)

result = checkList(dictORlist, key)
if isinstance(dictORlist, dict):
    for k in dictORlist.keys():
        data = dictORlist[k]
        if k == key:
            return True
        elif isinstance(data, dict):
            result = isKey(data, key)
        else:
            result = checkList(data, key)

if result == None:
    result = False
return result

Solution 6 - Python

I was thrown aback by what was possible in python2 vs python3. I will answer it based on what I ended up doing for python3. My objective was simple: check if a json response in dictionary format gave an error or not. My dictionary is called "token" and my key that I am looking for is "error"

if ((token.get('error', None)) is None):
    do something

I am looking for key "error" and if it was not there, then setting it to value of None, then checking is the value is None, if so proceed with my code. An else statement to handle the if I do have the key "error

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2057574View Question on Stackoverflow
Solution 1 - PythonDSMView Answer on Stackoverflow
Solution 2 - PythonLyncean PatelView Answer on Stackoverflow
Solution 3 - PythonRohit JainView Answer on Stackoverflow
Solution 4 - PythonRanvijay SachanView Answer on Stackoverflow
Solution 5 - PythonMarky0View Answer on Stackoverflow
Solution 6 - PythonFastGTRView Answer on Stackoverflow