How can I check if key exists in list of dicts in python?
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?
Solution 1:
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:
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:
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:
parsedData=[]
dataRow={}
if not any(d['url'] == dataRow['url'] for d in self.parsedData):
self.parsedData.append(dataRow)