如何遍历字典列表并显示特定键的值? [英] How to loop over a list of dicts and print values of a specific key?

查看:761
本文介绍了如何遍历字典列表并显示特定键的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to Python and have (what I know to be a very simple) question.

运行Python 3.4.

Running Python 3.4.

我有一个列表需要迭代,以提取特定信息.这是列表(称为零件)的示例(被截断的数千个项目):

I have a list that I need to iterate over and pull specific information out. Here is a sample (truncated, many thousands of items) of the list (called parts):

[{'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循环如下所示:

I want to do this using a for loop where I pull just the value after the 'id' key and print it to my console. A simple for loop looks like this:

for i in parts:
    print(i)

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

This, of course, prints all the information in the parts list again, which isn't what I want.

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

So I need to do something like:

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

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

This isn't correct because it just prints:

id
id
id
id
....etc

因此,我需要做一些我告诉它的事情:每次看到'id'时,都在其后打印值,但是我不确定如何构造该循环.

So I need to do something where I tell it "every time you see 'id', print the value after it, but I'm unsure how to structure that loop.

有人可以给我一些指导吗?

Can anyone give me some guidance?

推荐答案

如果我对您的理解正确.您正在寻找使用字典中的键获取值的方法.

If I understood you correctly. You are looking for fetching a value using key from a dict.

例如:

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

输出:

phwl
a06c5

Python词典中的更多信息

MoreInfo in Python Dictionaries

这篇关于如何遍历字典列表并显示特定键的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆