【问题标题】:How to extract the value from a nested dictionary within a nested list in python如何从python中嵌套列表中的嵌套字典中提取值
【发布时间】:2019-04-28 19:28:30
【问题描述】:

以下是我的代码sn-p。我正在尝试从嵌套列表中的嵌套字典中提取“字符串”和“分数”的值。我该如何做到这一点?

预期输出将是“对象元素”和“1.0”

[{'Form': [{'string': 'object element', 'score': 1.0,}],
  'types': ['http://google.com'],
'threshold':34}]

【问题讨论】:

  • 你试过什么?您希望在循环中完成此操作,还是简单地提取第一个(仅)'string''score' 值的值?另外,我认为最后的大括号可能有点混乱?
  • 我尝试先通过 reduce 函数展平列表,然后尝试通过列表索引解包值,但没有运气。是的,我希望在循环中完成。

标签: python python-3.x dictionary


【解决方案1】:

这应该可以工作

data = [{'Form': [{'string': 'object element', 'score': 1.0,}], 'types': ['http://google.com'], 'threshold':34},{'Form': [{'string': 'data store', 'score': 0.9,}], 'types': ['http://google.com'], 'threshold':23}]

for d in data:
    print(d['Form'][0]['string'])
    print(d['Form'][0]['score'])

【讨论】:

  • 谢谢@Nithin。实际上我错过了清楚地说明我的问题。理想情况下,我希望循环中的解决方案因为我的代码格式如下[{'Form': [{'string': 'object element', 'score': 1.0,}], 'types': ['http://google.com'], 'threshold':34},{'Form': [{'string': 'data store', 'score': 0.9,}], 'types': ['http://google.com'], 'threshold':23}]
  • 非常感谢@Nithin。这正是我想要的。
猜你喜欢
  • 2015-10-15
  • 2015-11-28
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多