【问题标题】:How to loop over a list of dicts and print values of a specific key?如何遍历字典列表并打印特定键的值?
【发布时间】:2018-10-05 18:54:13
【问题描述】:

我是 Python 新手,并且有(我知道这是一个非常简单的)问题。

运行 Python 3.4。

我有一个需要迭代并提取特定信息的列表。这是列表(称为部分)的示例(截断,数千个项目):

[{'state': 'DEAD',
  'id': 'phwl',
  'type_name': 'GAME',
  'unit_structure': 'lattice',
  'vendor': 'Downward',
  'type_id': 'shiftable'
  'weight': 'heavy'},
 {'state': 'ALIVE',
  'id': 'a06c5',
  'type_name': 'BOARD',
  'unit_structure': 'frame',
  'vendor': 'Sniggles',
  'weight': 'light'}]

我想使用 for 循环来执行此操作,在该循环中我只提取 'id' 键之后的值并将其打印到我的控制台。一个简单的 for 循环如下所示:

for i in parts:
    print(i)

这当然会再次打印零件清单中的所有信息,这不是我想要的。

所以我需要做类似的事情:

for i in parts:
    i = 'id'
    print(i)

这是不正确的,因为它只是打印:

id
id
id
id
....etc

所以我需要做一些事情,告诉它“每次你看到'id',打印它后面的值,但我不确定如何构造那个循环。

谁能给我一些指导?

【问题讨论】:

  • 只需使用 print(i['id']),它会为您提供与该 id 相关的值。
  • 是的,这是正确的。

标签: python python-3.x loops dictionary


【解决方案1】:

如果我理解正确的话。您正在寻找使用字典中的键获取值。

例如:

for i in parts:
    print(i["id"])   #or print(i.get("id"))

输出:

phwl
a06c5

MoreInfo in Python Dictionaries

【讨论】:

  • 是的,这是正确的。如果我想同时打印“id”和“type_name”怎么办?
  • 知道了:for i in part: print((i["serial_id"]), (i[type_name]))
猜你喜欢
  • 1970-01-01
  • 2016-10-10
  • 2018-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-04
  • 1970-01-01
相关资源
最近更新 更多