循环遍历python中的dicts列表

时间:2017-07-22 16:37:26

标签: python list loops dictionary iteration

有人可以通过下面列出的项目帮助我了解如何dict吗? 我在list内收到[ { "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

当前代码:

AmqpOutboundEndpoint

3 个答案:

答案 0 :(得分:0)

您可以使用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

答案 1 :(得分:0)

您的数据看起来是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

答案 2 :(得分:0)

对于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