3

我是编程和 python 的新手,我不知道如何解决这个问题。

 my_dict  = {'tiger': ['claws', 'sharp teeth', 'four legs', 'stripes'],
       'elephant': ['trunk', 'four legs', 'big ears', 'gray skin'],
       'human': ['two legs', 'funny looking ears', 'a sense of humor']
       }

new_dict = {}

for k, v in my_dict.items():
    new_v = v + "WOW"
    new_dict[k] = new_v

print(new_dict)

我想用添加的短语制作一个新字典,但我收到一个错误“只能将列表(不是“str”)连接到列表”,但是当我每个键只使用一个值时,程序可以工作。有什么解决办法吗?

4

2 回答 2

2

您可以将一个列表连接到另一个列表,如下所示:

if __name__ == '__main__':
    my_dict  = {'tiger': ['claws', 'sharp teeth', 'four legs', 'stripes'],
       'elephant': ['trunk', 'four legs', 'big ears', 'gray skin'],
       'human': ['two legs', 'funny looking ears', 'a sense of humor']
       }

    new_dict = {}
    
    for k, v in my_dict.items():
        new_v = v + ["WOW"]
        new_dict[k] = new_v
    
    print(new_dict)

{'老虎': ['爪子', '尖牙', '四腿', '条纹', 'WOW'], '大象': ['树干', '四腿', '大耳朵', '灰色skin', 'WOW'], 'human': ['两条腿', '有趣的耳朵', '幽默感', 'WOW']}

于 2021-02-03T13:45:48.727 回答
0

使用列表,您只能连接列表。

#So here you're trying to concatenate a list with the string
my_dict['tiger'] + 'WOW' # this won't work as one is string and other is List.
my_dict['tiger'] + ['WOW'] # this will work as both are of same type and concatenation will happen.
于 2021-02-03T13:55:03.553 回答