【问题标题】:python nested lists/dictionaries and popping valuespython嵌套列表/字典和弹出值
【发布时间】:2015-08-03 15:25:23
【问题描述】:

对于这是一个新手问题提前道歉。我刚刚开始编写 python,我一直对从嵌套字典/列表中弹出值感到困惑,所以我感谢任何帮助!

我有这个示例 json 数据:

{ "scans": [
   { "status": "completed", "starttime": "20150803T000000", "id":533},
   { "status": "completed", "starttime": "20150803T000000", "id":539}
] }

我想从“扫描”键中弹出“id”。

def listscans():
  response = requests.get(scansurl + "scans", headers=headers, verify=False)
  json_data = json.loads(response.text)
  print json.dumps(json_data['scans']['id'], indent=2)

似乎不起作用,因为嵌套的键/值在列表中。即

>>> print json.dumps(json_data['scans']['id'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str

谁能指出我正确的方向来让它工作?我的长期目标是创建一个 for 循环,将所有 id 放入另一个字典或列表中,我可以将其用于另一个函数。

【问题讨论】:

  • 从您上次的评论看来,您似乎已经对需要做什么有了一个很好的了解。为什么不尝试编写代码并向我们展示您的尝试?
  • 我想我不会用一百万个失败的例子来抨击这个帖子,我试图为有类似问题的未来读者保持简洁。

标签: python dictionary nested-lists


【解决方案1】:

json_data['scans'] 返回一个字典列表,您正在尝试使用 str 索引列表,即[]["id"],但由于明显原因而失败,因此您需要使用索引来获取每个子元素:

print json_data['scans'][0]['id'] # -> first dict
print json_data['scans'][1]['id'] # -> second dict

或者查看所有 id 对使用 json_data["scans"] 返回的 dicts 列表的迭代:

for dct in json_data["scans"]:
    print(dct["id"]) 

保存追加到列表:

all_ids = []
for dct in json_data["scans"]:
    all_ids.append(dct["id"])

或使用列表组合:

all_ids = [dct["id"] for dct in json_data["scans"]]

如果密钥id 可能不在每个字典中,请在访问之前使用in 检查:

all_ids = [dct["id"] for dct in json_data["scans"] if "id" in dct]

【讨论】:

  • 完美!我在 ['scans'] 之后缺少列表索引位置。现在有道理了。我对第二个例子有点困惑。的: print(d["id"]) 是 d 的索引位置吗?我认为您必须将索引位置放在括号内以弹出值
  • @dobbs,我们在循环中遍历列表,所以每个d 都是列表中的每个实际element/dict,所以我们通过键id 访问字典以获取每个值
【解决方案2】:

在这里,您如何遍历项目并提取所有 id:

json_data = ...
ids = []
for scan in json_data['scans']:
    id = scan.pop('id')
    # you can use get instead of pop
    # then your initial data would not be changed, 
    # but you'll still have the ids
    # id = scan.get('id')
    ids.append();

这种方法也可以:

ids = [item.pop('id') for item in json_data['scans']]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 2021-10-24
    • 2017-08-12
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多