Netro
Netro

Reputation: 7297

Search in python list of dict

I have a list (l) of dictionaries {"id": id, "class": class, "parameter": parameter}. I have to do this,

for each value of class:
    parameter = getParameter(class) //we can get different parameter for same class
    if {"class":class, "parameter":parameter} not in l:
         increment id and do l.append({"id": id, "class": class, "parameter": parameter})

Here dict in list has 3 keys, where as i have to search in list with 2 keys. How can i validate 'if' condition?

Upvotes: 0

Views: 300

Answers (4)

l4mpi
l4mpi

Reputation: 5149

If I understand correctly your problem is deciding if there is already an entry with the given values for class and parameter? You will have to write an expression that searches the list for you, like this:

def search_list(thedict, thelist):
    return any(x["class"] == thedict["class"]
               and x["parameter"] == thedict["parameter"]
               for x in thelist)

The function returns True if an entry is found. Call it like this:

if not search_list({"class": class, "parameter": parameter}, l):
    #the item was not found - do stuff

Upvotes: 5

Emmanuel
Emmanuel

Reputation: 14209

I think with set comparison, you can get rid of that:

>>> d1 = {"id": 1, "class": 3, "parameter": 4}
>>> d2 = {"id": 1, "class": 3}
>>> set(d2.items()) < set(d1.items())
True
>>> 

Upvotes: 0

eumiro
eumiro

Reputation: 212825

if not any(d['attr1'] == val1 and d['attr2'] == val2 for d in l):

tests whether there is not dict d in list l with its attr1 equal to val1 and attr2 equal to val2.

The advantage is that it stops the iteration as soon as match is found.

Upvotes: 3

John
John

Reputation: 13699

if {"class":class, "parameter":parameter} not in [{'class':d['class'], 'parameter':d['parameter']} for d in l]:

You'll probably not want to calculate the list every time the condition is checked, do that outside of the loop.

Upvotes: 0

Related Questions