python - 创建一个新的字典值列表,其键与单独列表中的项目匹配

标签 python list dictionary

该字典将农场动物存储为键,将它们的位置存储为值。

id_name_dict = {
    'cat': 'barn', 'dog': 'field', 'chicken': 'coop',
    'sheep': 'pasture', 'horse': 'barn', 'cow': 'barn'
}

此列表存储我想知道其位置的农场动物的名称

wanted_farm_animals = ['cat,', 'dog', 'horse']

所需的输出是一个包含wanted_farm_animals位置的新列表

n = ['barn', 'field', 'barn']

这是我尝试执行此操作的代码

n = []
for animal, location in id_name_dict.items():
    for a in wanted_farm_animals:
        if a == animal:
            n.append(location)
print(n)

但是,输出并不完整。只是

['field', 'barn']

如何获得正确的所需输出?

最佳答案

简单的列表理解怎么样?

id_name_dict = {
    'cat': 'barn', 'dog': 'field', 'chicken': 'coop',
    'sheep': 'pasture', 'horse': 'barn', 'cow': 'barn'
}    
wanted_farm_animals = ['cat', 'dog', 'horse']

result = [v for k,v in id_name_dict.items() if k in wanted_farm_animals]
# ['barn', 'field', 'barn']

关于python - 创建一个新的字典值列表,其键与单独列表中的项目匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54986276/

相关文章:

javascript - Angular 列表引用在项目删除时未更新

python - python中的列表理解

python - 如何将嵌套数据示例中的两个值抽象到 pandas Dataframe 中?

java - 如何将持久对象映射到DTO?

python - Numpy 数组到字典

python - 是 否 回答系统/游戏中 python 中 if 语句的问题

python - 将数字分配给给定字符串的字母

python - 用pygame制作的游戏可以提交到steam吗?

C# 列表重复项

python - 为文件夹中的所有 python 模块运行我的所有 doctests,而不会因为错误的导入而失败