Possible Duplicate:
What's the best way to search for a Python dictionary value in a list of dictionaries?
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 loop through the list of results
checking if the value is in dict
, e.g.
for r in results:
if r in my_dict_list:
print "ok"
for r in result:
for d in dict:
if d['value'] == r:
print "ok"
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 a value is found. any
will go through all the items in dict
.
Also, don't call a list dict
and don't use built-in type/function names as variables.
Well, in your case, your dict variable is not a dictionnary, it's a list of 3 dictionnaries, each dictionnary containing 2 keys (text and value). Note that I supposed that either value is a variable or zthat you forgot 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 that's 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 understand correctly, maybe you wanted to create a dictionnary associating first value to number 1 ?
精彩评论