Alexander Viktorsson
Alexander Viktorsson

Reputation: 27

How to find a value inside a list that is inside a dictionary

I am trying to find a value inside a list that is inside a dictionary whitout using the key and the purpose is so that i cant add the same name to the dictionary.

The dictionary looks something like this:

Dict={'1_number': ['1_name'], '2_number': ['2_name', '3_name']}

so i am trying to check if 3_name exists inside the dictionary.

Also trying to display 2_number by searching for it with 2_name, that is displaying the key by finding it with one of its values.

Upvotes: 1

Views: 135

Answers (3)

greole
greole

Reputation: 4771

You can iterate of the values of a dictionary and check for the pressence of the wanted list value:

>>> def find_in_dict(d, name):
>>>    for k,vals in d.iteritems():
>>>        if name in vals:
>>>           return k
>>>    else:
>>>       return False

>>> find_in_dict(d,'3_name')
'2_number'
>>> find_in_dict(d,'4_name')
False

Upvotes: 1

Abhijit
Abhijit

Reputation: 63737

You can actually combine list comprehension to iterate over the values of a dictionary with any for short circuit evaluation to search an item to get the desired result

>>> any('3_name' in item for item in Dict.values())
True

alternatively, if you are interested to return all instances of dictionaries which have the concerned item, just ensure that the condition to check the item in its value is within the if statement and key value pair is returned as part of the filter List Comprehension

>>> [(k, v) for k, v in Dict.items() if '3_name' in v]
[('2_number', ['2_name', '3_name'])]

Finally, if you are sure there is one and only one item, or you would like to return the first hit, use a generator with a next

>>> next((k, v) for k, v in Dict.items() if '3_name' in v)
('2_number', ['2_name', '3_name'])

Upvotes: 4

Cory Kramer
Cory Kramer

Reputation: 117866

You can use a list comprehension to search the values of the dictionary, then return a tuple of (key, value) if you find the key corresponding to the value you are searching for.

d = {'1_number': ['1_name'], '2_number': ['2_name', '3_name']}
search = '3_name'

>>> [(key, value) for key, value in d.items() if search in value]
[('2_number', ['2_name', '3_name'])]

Upvotes: 0

Related Questions