1

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}]

1 Answer 1

4

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')

Sign up to request clarification or add additional context in comments.

3 Comments

Awesome - thanks a lot. works, and it's a pretty little oneliner
I realized this is the equivalent of [n for n in nutrients where n.get('name') == 'Manganese,Mn'] which is incidentally the way I prefer, but I speed tested it and this [n for n..] "pythonic" way is actually a bit faster in this case as well
Yes, they are equivalent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.