我是编程和 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”)连接到列表”,但是当我每个键只使用一个值时,程序可以正常工作。有什么解决办法吗?
最佳答案
您可以将一个列表连接到另一个列表,如下所示:
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)
{'tiger': ['claws', 'sharp teeth', 'four legs', 'stripes', 'WOW'], 'elephant': ['trunk', 'four legs', 'big ears', 'gray skin', 'WOW'], 'human': ['two legs', 'funny looking ears', 'a sense of humor', 'WOW']}
关于Python - 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66028747/