如何访问列表中的字典类型项(python或javascript)

时间:2016-08-13 10:57:14

标签: python json list dictionary

我在django'Food'模型中的'营养'JSONField中存储了一些数据。

底部的一些示例数据结构。

数据是Food.nutrients,但我不知道如何/最佳方式访问营养素列表中的特定项目 - 其结构类似于[{dict type item},{dict type item},...] 。

每个项目都是一个带有'name'键和'nutrient_id'键的字典,我感觉可以帮我挑选出我想要的项目。然后从项目字典中我想获得键'value'的值(我没有将键命名为'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 个答案:

答案 0 :(得分:3)

假设您有nutrients中的词典列表。现在,您可以筛选列表以查找与特定键匹配的具有特定值的项目。例如,要找到name具有“锰,锰”字典,您可以这样做:

matches = filter(lambda n: n.get('name') == 'Manganese, Mn', nutrients)

现在matches列表应包含name键中包含“锰,锰”的营养素。

您可以使用索引matches[0]访问第一个营养素。现在您也可以访问其他键,例如matches[0].get('value')