【问题标题】:Making a new list of dictionary values whose keys match items in a seperate list制作一个新的字典值列表,其键与单独列表中的项目匹配
【发布时间】:2019-03-04 15:23:15
【问题描述】:

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

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']

如何获得正确的期望输出?

【问题讨论】:

  • @meowgoesthedog 鉴于您的用户名,您必须是农场动物方面的专家;)
  • wanted_farm_animals 列表中的“猫”后面多了一个逗号
  • 知道了!谢谢。

标签: python list dictionary


【解决方案1】:

简单的列表理解怎么样?

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']

【讨论】:

  • @mkrieger1,如果animal 不在id_name_dict 中怎么办?喜欢wanted_farm_animals = ['cat,', 'dog', 'horse', 'mouse']。所以我们依赖于匹配/相交的键
【解决方案2】:

您可以将wanted_farm_animals 列表映射到绑定到id_name_dict dict 的dict.get 方法:

n = list(map(id_name_dict.get, wanted_farm_animals))

通过使用dict.get 方法,对于wanted_farm_animals 列表中但不在id_name_dict 字典的键中的项目,您将获得None 的默认值而不是KeyError 异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 2020-03-31
    • 2016-09-30
    • 1970-01-01
    • 2021-11-17
    • 2023-01-20
    相关资源
    最近更新 更多