Python - 字典

标签 python dictionary

我是编程和 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/

相关文章:

python - 使用命令行参数在 C++ 中运行 python .py 文件

python - Django:将 CreateView 与 HTML 模板一起使用时未保存图像

python - 在 Python 中提取序列

python - Gstreamer1.0/Python 3 中的 Cairooverlay

c++ - 为 map 重载 '<' 运算符时遇到问题

c# - 词典 - 添加注释以驱动智能感知

python - Pandas 数据框格式不正确

ios - 获取简短的 Google map URL 以在 iOS 中共享

c++ - 如何检查对象的属性更新是否存在 std::map 键,否则插入一个新键?

c++ - 如何在 map 和 unordered_map 之间进行选择?