【问题标题】:Looping through a list of dicts in python循环遍历python中的dicts列表
【发布时间】:2017-07-22 16:37:25
【问题描述】:

有人可以通过下面列出的项目帮助我了解如何loop 吗? 我在list 中得到了dict。 尝试学习如何自己获取每个项目

这是我连接时得到的结果:

[
    {
  "Index": "NASDAQ",
  "ExtHrsChange": "-0.22",
  "LastTradePrice": "972.92",
  "LastTradeWithCurrency": "972.92",
 }
]

当前代码:

for line in quotes: 
    (key, value) = line.split() 
    if "LastTradePrice" in key: 
        print key

【问题讨论】:

  • 这是我的循环:for line in quotes: (key, value) = line.split() if "LastTradePrice" in key: print key
  • 那么你发现了吗?

标签: python list loops dictionary iteration


【解决方案1】:

您可以使用 for 循环获取列表中的每个字典,然后使用内置的 items() 方法从字典中拆分键和值:

l = [
 {
    "Index": "NASDAQ",
    "ExtHrsChange": "-0.22",
    "LastTradePrice": "972.92",
    "LastTradeWithCurrency": "972.92",
 }
]

for i in l:
    if "LastTradePrice" in i:
        for a, b in i.items():
            print a, b

【讨论】:

  • 非常感谢您的帮助,它现在对我有用。这正是我想学习的。
  • @JZi 请接受此答案,以便其他用户知道您的帖子有答案。
【解决方案2】:

您的数据看起来是 json 格式的字符串,除了字典列表末尾的一个额外逗号(也许您手动输入了这个?)。使用 json 模块对其进行解析,然后遍历字典列表:

raw_data = '''\
[
    {
  "Index": "NASDAQ",
  "ExtHrsChange": "-0.22",
  "LastTradePrice": "972.92",
  "LastTradeWithCurrency": "972.92"
 }
]'''

import json
data = json.loads(raw_data)

for item in data:
    for key,value in item.items():
        print(key,value)
Index NASDAQ
ExtHrsChange -0.22
LastTradeWithCurrency 972.92
LastTradePrice 972.92

【讨论】:

  • 非常感谢您的帮助。一旦我添加了 josn.loads 并遍历数据,它就对我有用。
【解决方案3】:

对于 Python2,请尝试 iteritems():

dict_list = [
    {
    "Index": "NASDAQ",
    "ExtHrsChange": "-0.22",
    "LastTradePrice": "972.92",
    "LastTradeWithCurrency": "972.92"
    }
]

for entry in dict_list:
    for key, value in entry.iteritems():
        print key, value

【讨论】:

    猜你喜欢
    • 2018-10-26
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 2023-03-09
    • 2014-06-26
    相关资源
    最近更新 更多