简体   繁体   English

Python 中是否有用于访问 for 循环中的字典值的简短形式?

[英]Is there a short form for accessing dictionary values in for loop in Python?

Is there a short form for accessing dictionary values in for loop in Python? Python 中是否有用于访问 for 循环中的字典值的简短形式?

I have the following example code:我有以下示例代码:

dict = [{"name": "testdata"}, {"name": "testdata2"}]

for x in dict:
    print(x["name"])

Is there a way to write the dictionary key directly into the line of the for loop, eg有没有办法将字典键直接写入for循环的行中,例如

dict = [{"name": "testdata"}, {"name": "testdata2"}]

for x in dict["name"]:
    print(x)

which obviously does not work.这显然是行不通的。 But the main idea is that x should already be the string "testdata" or "testdata2".但主要思想是 x 应该已经是字符串“testdata”或“testdata2”。 I want to avoid this:我想避免这种情况:

dict = [{"name": "testdata"}, {"name": "testdata2"}]

for x in dict:
    x = x["name"]

You can't destructure a dict on assignment, so the only way would be to loop over an iterable that contains only the one value you want, eg:你不能在赋值时解构字典,所以唯一的方法是遍历一个只包含你想要的一个值的可迭代对象,例如:

for x in (i['name'] for i in dict):
    ...

or:或者:

from operator import itemgetter

for x in map(itemgetter('name'), dict):
    ...

You won't get around calling the key for each element but you can do it in a list comprehension to convert your list of dictionaries to a list of 'name' elements and then loop through that:你不会绕过为每个元素调用键,但你可以在列表理解中完成它,将你的字典列表转换为'name'元素列表,然后循环遍历它:

dict = [{"name": "testdata"}, {"name": "testdata2"}]

for name in [x["name"] for x in dict]:
    print(name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM