1

I am quite new to Python and I am struggling with a simple code that creates dictionaries and tries to print the information inside it. I created a dictionary named pets that contains the name of the pets as keys. The values are dictionaries that contain pieces of information about the pets.

I want to print in one sentence the name of the pet, and the information about the pet.

As shown in my code below, I am trying to create a for loop that will print a sentence for each pet.

pets = {
    'maxi': {
    'owner':'Laura',
     'favorite food':'wiskas'
    },
    'chester': {
    'owner':'Emilia',
    'favorite food':'lula'
        }
    }

print(pets)
for name,info in pets.items():
    print(name + "'s owner and favorite food are " + name['owner'] + ' and ' + name['favorite food'])

I get the following error:

Traceback (most recent call last): File "pets.py", line 14, in print(name + "'s owner and favorite food are " + name['owner'] + ' and ' + name ['favorite food']) TypeError: string indices must be integers

4

2 回答 2

2

当你使用for name,info in pets.items()循环时,name实际上是一个字符串。这就是您收到该错误的原因:您正在尝试访问字符串的元素。您需要使用info来访问内部值:

for name, info in pets.items():
    print(name + '\'s owner and favorite food are ' + info['owner'] + ' and ' + info['favorite food'])
于 2019-10-16T12:26:56.040 回答
0

尝试这个

for x in pets:
    print(x + "'s owner and favorite food are " + pets[x]['owner'] + ' ' + pets[x]['favorite food'])    

>>> maxi's owner and favorite food are Laura wiskas
>>> chester's owner and favorite food are Emilia lula

你的错误是 "name['owner'] + ' and ' + name['favorite food']" <- 这是因为你必须首先参考 dict 中的项目,在我们的例子中是 "x" 或 "name"不管你想要什么,然后你想输入他的钥匙来取它的名字,所以,pets[name]['owner'] 除了你拿另一个钥匙,在我们的例子中是“最喜欢的食物”,我希望这个为你清除一些东西:D

于 2019-10-16T12:23:55.377 回答