首页 > 解决方案 > 如何将dict与python中的列表进行比较

问题描述

假设我们有这些dictlist

dict = {"a": 20, "b": 3, "c": 50}
list = ["a", "z", "d", "c"]

我需要一种方法来获得下面的输出,如下所示:只有当键在列表中时,dict 中键的值才会被求和:

70
a c

这样做的方法是什么?我认为是ifelse比较,但我的知识延伸到这里。

标签: python

解决方案


简单易懂的替代方案:

dict = {"a": 20, "b": 3, "c": 50}
# this creates your dictionary
list = ["a", "z", "d", "c"]
# this creates your list
finalAnswerNumber = 0
# this variable will become "70" in your example
finalAnswerKeys = ""
# This variable is what would output "a" and "c" in your example
for stuff in list:
    # This for statement creates a "stuff" for every element of the list
    if stuff in dict:
        # This if statement checks if "stuff" is a key in dict
        finalAnswerNumber+=dict[stuff]
        # This adds the value for the key "stuff" to the variable finalAnswerNumver, it breaks is the value is a not a number
        finalAnswerKeys+=stuff+" "
        # This adds the "stuff" and a space to the variable finalAnswerKeys
print(finalAnswerNumber)
# The following print functions aren't necessary if you would prefer not to print the values
# this prints the number (in this case 70)
print(finalAnswerKeys)
# this posts the keys (in this case "a" and "c")

运行此代码后的输出应如下所示

70
a c 

推荐阅读