The Condor
The Condor

Reputation: 1054

How do I compare a string with a dictionary element?

how can I check if a string is inside a dictionary? I tried but it gives me an error, I cannot use string indexes.

My list is something like this:

o_list = [{'h': 4, 'name': 'a'},{'h': 6, 'name': 'b'},{'h': 1, 'name': 'c'}]

and I have to check it with this variable:

min_node = a

I tried this way:

for i, elem in enumerate(o_list):
    if min_node in o_list[i]['name']:
        return min_node
    else:
        return 'error in retrieving min F'

Upvotes: 2

Views: 98

Answers (3)

Xavier Combelle
Xavier Combelle

Reputation: 11235

I think your problem is that a is a variable instead bing the string 'a'

this work

o_list = [{'h': 4, 'name': 'a'},{'h': 6, 'name': 'b'},{'h': 1, 'name': 'c'}]

min_node = 'a'

def f():
  for i, elem in enumerate(o_list):
    if min_node == o_list[i]['name']:
        return min_node
    else:
        return 'error in retrieving min F'

print f()

however it would be more elegant to do the following

o_list = [{'h': 4, 'name': 'a'},{'h': 6, 'name': 'b'},{'h': 1, 'name': 'c'}]

min_node = 'a'

def f():
  for elem in o_list:
    if min_node == elem["name"]:
        return min_node
    else:
        return 'error in retrieving min F'

print f()

Upvotes: 2

Joseph Victor Zammit
Joseph Victor Zammit

Reputation: 15320

Not sure why you are using enumerate; the below snippet builds a list called names and simply uses the in clause to check whether a name is in such list:

In [2]: o_list = [{'h': 4, 'name': 'a'},{'h': 6, 'name': 'b'},{'h': 1, 'name': 'c'}]

In [3]: names = [item.get('name') for item in o_list] # build list

In [4]: names # show list contents
Out[4]: ['a', 'b', 'c']

In [5]: 'a' in names
Out[5]: True

In [6]: 'z' in names
Out[6]: False

Upvotes: 1

unutbu
unutbu

Reputation: 880747

if any(min_node in item['name'] for item in o_list):
    return min_node
else:
    return 'error in retrieving min F'

Upvotes: 0

Related Questions