在将字典嵌套在列表中时,出现TypeError:字符串索引必须为整数

问题描述 投票:0回答:1
friend_0 = {
    'first_name' : 'wong', 
    'last_name' : 'cap bawong', 
    'age' : 16, 
    }

friend_1 = {
    'first_name' : 'lele',
    'last_name' : 'cap meong',
    'age' : 46,
    }

friend_2 = {
    'first_name' : 'kucing',
    'last_name' : 'nan indah',
    'age' : 18
    }

people = [friend_0, friend_1, friend_2]

for person in people:
    for k in person.keys():
        **friend = f"{k['first_name'].title()} {k['last_name'].title()}"**
        print (f"\nName: {friend}")
        print (f"\tAge: {k['age']}")

我在以下行中出错:friend = f“ {k ['first_name']。title()}{k ['last_name']。title()}“

文件类型错误-字符串索引必须为整数

python-3.x string list dictionary indices
1个回答
0
投票

尝试此:

for person in people:
    friend = f"{person['first_name'].title()} {person['last_name'].title()}"
    print(f"\nName: {friend}")
    print(f"\tAge: {person['age']}")
© www.soinside.com 2019 - 2024. All rights reserved.