Reputation: 1296
I have some data stored in 'nutrients' JSONField in a django 'Food' model.
some sample datastructure at the bottom.
The data is Food.nutrients, but I don't know how/ best way access a particular item in the nutrients list - which is structured like [{dict type item},{dict type item},...].
Each item is a dictionary with a 'name' key and 'nutrient_id' key, which I feel could help me pick out the item that I want. And then from the item dictionary I want to get the value for key 'value' (I didn't name the key 'value').
[{u'dp': 1,
u'group': u'Minerals',
u'measures': [],
u'name': u'Manganese, Mn',
u'nutrient_id': 315,
u'se': u'',
u'sourcecode': [1],
u'unit': u'mg',
u'value': 0.094},
{u'dp': 1,
u'group': u'Minerals',
u'measures': [],
u'name': u'Selenium, Se',
u'nutrient_id': 317,
u'se': u'',
u'sourcecode': [1],
u'unit': u'\xb5g',
u'value': 0.4},
{u'dp': 1,
u'group': u'Vitamins',
u'measures': [],
u'name': u'Vitamin C, total ascorbic acid',
u'nutrient_id': 401,
u'se': u'',
u'sourcecode': [1],
u'unit': u'mg',
u'value': 4.0}]
Upvotes: 1
Views: 62
Reputation: 11906
Let's suppose, you have the list of dictionaries in nutrients
. Now you can filter the list to find the items matching a particular key with a specific value. For example, to find the dictionary with name
having "Manganese, Mn", you can do:
matches = filter(lambda n: n.get('name') == 'Manganese, Mn', nutrients)
Now the matches
list should contain the nutrients which contain "Manganese, Mn" in the name
key.
You can access the first nutrient using index - matches[0]
. Now you can access other keys too, like matches[0].get('value')
Upvotes: 4