【问题标题】:Given a list of strings, I want to add the values of a dictionary to a new dictionary if any of the values are equal to the values in the list [duplicate]给定一个字符串列表,如果任何值等于列表中的值,我想将字典的值添加到新字典中[重复]
【发布时间】:2019-06-03 15:15:43
【问题描述】:

例如:

my_dict = {1: "apple", 2: "pear", 3: "orange", 4: "apple", 5: "grape", 6: "mango", 7: "mango", 8: "pear", 9: "lemon"}
fruit_list = ["apple", "mango", "lemon"]

我想通过 my_dict 进行解析,如果 my_dict 中的值等于 fruit_list 中的任何一个值,则将该键和值添加到新字典中,因此输出字典为:

{1: "apple", 4:"apple", 6:"mango", 7:"mango", 9:"lemon"}

我已经厌倦了使用 enumerate 函数,但似乎没有得到输出。

谢谢!

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    你可以做一个字典理解:

    new_dict = {k: v for k, v in my_dict.items() if v in fruit_list}
    

    【讨论】:

      猜你喜欢
      • 2015-04-02
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-05
      • 1970-01-01
      • 2020-04-09
      相关资源
      最近更新 更多