如何在python中将dict与列表进行比较

2024-09-30 16:38:36 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我们有dictlist

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

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

70
a c

这样做的方法是什么?我在{}或{}比较中思考,但我的知识延伸到这里


Tags: 方法列表dictlist当键
3条回答

简单易懂的备选方案:

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 

备选方案:

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

val_sum = sum(v for k,v in d.items() if k in l) # 70 
keys = ' '.join(k for k,v in d.items() if k in l) # 'a c'

查找列表l和dict d键之间的并集。输出为{a, c}(<;-这是一个集合)。通过列表理解,在求和之前获取索引值:

>>> sum(d[i] for i in set(d.keys()).intersection(l))
70

相关问题 更多 >