繁体   English   中英

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

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

我正在尝试遍历嵌套在列表中的字典。 它看起来像这样:

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]

我想要这样的输出,但代码更简单:

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'])

但是,当我运行这个 for 循环时:

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

我得到这个输出:

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

我也试过这个 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)

我收到一个类型错误:

类型错误:字符串索引必须是整数。

事实上,当我在括号中使用整数时,它返回文本的一部分,而不是返回匹配键的值。 欢迎任何建议或帮助。 谢谢你。

没有理由循环两次,一次就足够了:

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