Alexander
Alexander

Reputation: 1378

Looking for a key value inside a list of dictionaries

I'm trying to write a function that as soon as it receives a number it will inform the user if its already inside the list, like so:

TodoList=[{'id':5} ,{'id':3}  ,{'id':6}];
def AddItem(id):
     if id in TodoList:
          print('inside');

But I don't know how to search if its inside a a list of dictionaries, how can I do that?

Upvotes: 1

Views: 66

Answers (4)

Dani Mesejo
Dani Mesejo

Reputation: 61900

You could use any:

TodoList=[{'id':5} ,{'id':3}  ,{'id':6}];
def AddItem(i):
     if any(i in d for d in TodoList):
          print('inside')

As a side-note do not use id as a variable name it shadows the built-in function id. If you want to search for a given value inside the dictionaries this will do as suggested by @DeepSpace:

def AddItem(i):
    if any(i in d.values() for d in TodoList):
        print('inside')


AddItem(5)

Output

inside

Upvotes: 0

Menilik Belay Woldeyes
Menilik Belay Woldeyes

Reputation: 369

You should use the safe dictionary method get().
Here is how you can solve this...

TodoList=[{'id':5} ,{'id':3}  ,{'id':6}];
def AddItem(id):
     values = [i.get('id') for i in TodoList]
     if id in values:
         return True
     return False

AddItem(2)
[OUT]: False

AddItem(3)
[Out]: True


Upvotes: 0

DeepSpace
DeepSpace

Reputation: 81594

A bit more efficient than the other answers since it will stop as soon as it finds a first match (and also supports the case where these dictionaries will have more key-value pairs):

TodoList = [{'id': 5}, {'id': 3}, {'id': 6}]

def AddItem(i):
    if any(d['id'] == i for d in TodoList):
        print('inside')

AddItem(5)

Upvotes: 1

cph_sto
cph_sto

Reputation: 7585

We create a list of all the values of the nested dictionaries and search them.

TodoList=[{'id':5} ,{'id':3}  ,{'id':6}];

def AddItem(id):
     values_TodoList = [i['id'] for i in TodoList]
     if id in values_TodoList:
          print('inside');
     else:
          print('not inside')

AddItem(5)
    inside

AddItem(10)
    not inside

Upvotes: 0

Related Questions