简体   繁体   English

如何遍历嵌套在列表中的字典

[英]How to loop through a dictionary nested in a list

I am trying to loop through a dictionary that is nested in a list.我正在尝试遍历嵌套在列表中的字典。 It looks like this:它看起来像这样:

person_0 = {
    'first_name' : 'joe',
    'last_name' : 'schmoe',
    'age' : '35',
    'city' : 'houston',
    }

person_1 = {
    'first_name' : 'angela',
    'last_name' : 'yee',
    'age' : '42',
    'city' : 'new york',
    }

person_2 = {
    'first_name' : 'erykah',
    'last_name' : 'badu',
    'age' : '50',
    'city' : 'dallas',
    }

people = [person_0, person_1, person_2]

I want an output like this but with simpler code:我想要这样的输出,但代码更简单:

print(person_0['first_name'] + " " + person_0['last_name'])
print(person_1['first_name'] + " " + person_1['last_name'])
print(person_2['first_name'] + " " + person_2['last_name'])

However, when I run this for loop:但是,当我运行这个 for 循环时:

for persons in people:
    for person_info in persons.keys():
        full_name = persons['first_name'] +" "+ persons['last_name']
        print(full_name)

I get this output:我得到这个输出:

joe schmoe
joe schmoe
joe schmoe
joe schmoe
angela yee
angela yee
angela yee
angela yee
erykah badu
erykah badu
erykah badu
erykah badu

I also tried this for loop:我也试过这个 for 循环:

people = [person_0, person_1, person_2]
#print(people)
for persons in people:
    for person, person_info in persons.items():
        full_name = person_info['first_name'] +" "+ person_info['last_name']
        print(full_name)

I receive a type error:我收到一个类型错误:

TypeError: string indices must be integers.类型错误:字符串索引必须是整数。

In fact when I use an integer with in the brackets it returns a slice of the text instead of returning the value of the matching key.事实上,当我在括号中使用整数时,它返回文本的一部分,而不是返回匹配键的值。 Any suggestions or help is welcomed.欢迎任何建议或帮助。 Thank you.谢谢你。

There is no reason to loop twice, once is enough :没有理由循环两次,一次就足够了:

people = [{'first_name': 'joe', 'last_name': 'schmoe', 'age': '35', 'city': 'houston'},
          {'first_name': 'angela', 'last_name': 'yee', 'age': '42', 'city': 'new york'},
          {'first_name': 'erykah', 'last_name': 'badu', 'age': '50', 'city': 'dallas'}]

for person in people:
    print(person['first_name'], person['last_name'])

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

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