Python - value in a dictionary list

Possible duplicate:
What is the best way to find the value of a Python dictionary in a dictionary list?

I have a list of dictionaries in the form

my_dict_list = [] my_dict_list.append({'text':'first value', 'value':'number 1'}) my_dict_list.append({'text':'second value', 'value':'number 2'}) my_dict_list.append({'text':'third value', 'value':'number 3'}) 

I also have another list in the form:

 results = ['number 1', 'number 4'] 

how can I scroll through the list of results if the value is in a dict , for example.

 for r in results: if r in my_dict_list: print "ok" 
+4
source share
3 answers
 for r in result: for d in dict: if d['value'] == r: print "ok" 
+5
source

map(lambda string: any(map(lambda item: item['value'] == string, dict)), results) returns a list of [True, False] for the given results . Although using for is more appropriate here, because you can break the nested loop when the value is found. any will go through all the elements in the dict .

Also, do not call the dict list or use the built-in type / function names as variables.

+3
source

Well, in your case, your dict variable is not a dictionary, it is a list of 3 dictionaries, each of which contains 2 keys (text and value). Note that I suggested that either the value is a variable or z that you forgot the quotes around it (I added them here)

 [{'text': 'second value', 'value': 'number 2'}, {'text': 'third value', 'value': 'number 3'}, {'text': 'first value', 'value': 'number 1'}] 

If this is what you expected, then you can use something like:

 mySetOfValues=set([x['value'] for x in my_dict_list]) for r in results: if r in mySetOfValues: print 'ok' 

However, if I understood correctly, perhaps you wanted to create a dictionnary by matching the first value with number 1?

+1
source

Source: https://habr.com/ru/post/1348117/


All Articles