I have a really weird thing happening. I am trying to loop through a set of dictionaries to find all of the items with a specific value related to a field key. Take the following:
ex_set is an output from a mysql system that I do not have control over. If I had to re-create it using python, it would be something like:
dict_a [ 'field' ] = 'fruit'
dict_a [ 'value' ] = 'apple'
dict_b [ 'field' ] = 'fruit'
dict_b [ 'value' ] = 'berry'
ex_set = set()
ex_set.add (dict_a,dict_b)
The important thing is how the set looks when I pprint it.
pprint (ex_set)
OUTPUTS> ({'field' : 'fruit',
'value' : 'apple'},
'field' : 'fruit'},
'value' : 'berry'})
i = 0
while len ( ex_set ) > i:
for k , v in ex_set [i].iteritems ( ):
if v == 'fruit':
pprint ( ex_set[i] )
i += 1
The problem is that the printing of this does not print all of the dictionaries that have a value = “fruit”.
Is there a better way to search through a set of dictionaries? The set that I am searching through has 3 key/value combinations in each dictionary and about 30k dictionaries. This works about 25% of the time and I can’t figure out why it is only returning about 20% of the matches.
Thanks for the help!
Based on your description you are seeking something like:
Also, in addition to the fact, that your example isn’t valid python, ex_set certainly can’t be a
set, assets'scant containdictionariesas they are unhashable. I would consider renaming it to something more suitable: