Iterating through a collection of dictionaries - python - basic search
I have a really strange thing. I am trying to iterate over a set of dictionaries to find all items with a specific value associated with a field. Take the following:
ex_set is a mysql logout that I have no control over. If I had to re-create it with 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)
What matters is how the kit looks when I print it out.
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 printing this does not print all dictionaries that have value = "fruit".
Is there a better way to search through a set of dictionaries? The set I am looking at 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 only returns 20% of the matches.
Thanks for the help!
source to share
Based on your description, you are looking for something like:
In [6]: ex_set = ({'fruit':'apple',
...: 'value':'fruit'},
...: {'fruit':'fruit'},
...: {'apple':'apple'})
In [7]: for d in ex_set:
...: if 'fruit' in d.values():
...: print(d)
...:
{'fruit': 'apple', 'value': 'fruit'}
{'fruit': 'fruit'}
Also, in addition to the fact that your example is not valid python, ex_set certainly cannot be set
, as it sets's
cannot contain dictionaries
, since they are not shaken. I would like to rename it to something more appropriate:
In [8]: set([{}])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-7facc835553f> in <module>()
----> 1 set([{}])
TypeError: unhashable type: 'dict'
source to share