繁体   English   中英

如何将值列表加入Python字典?

[英]How do I join a list of values into a Python dictionary?

我试图在Python 3中将列表加入字典,并返回键值的总和。

到目前为止,我还不能加入两者,我已经尝试使用getset并没有成功。

我还尝试了将链接listy和dict2设置为set的for循环,如下所示:

dict2 = {
1: "A",
2: "B",
3: "C"
}

listy = ['A', 'M', 'B', 'A']

for k in dict2:
    if set(listy) & set(dict2[value]):
        print(dict2.key)

这是我在IPython中遇到的错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-291-5a5e2eb8d7f8> in <module>
     10 
     11 for k in dict2:
---> 12     if set(listy) & set(dict2[value]):
     13         print(dict2.key)
     14 

TypeError: unhashable type: 'list'

您可以使用列表理解:

[x for x in listy if x in set(dict2.values())]

在代码中

dict2 = {
1: "A",
2: "B",
3: "C"
}

listy = ['A', 'M', 'B', 'A']

print([x for x in listy if x in set(dict2.values())])
# ['A', 'B', 'A']

您可能打算使用dict[k]而不是dict2[value]

另外,词典的条目包含单个值(不是列表),因此您可以使用in运算符:

例如:

 # if listy is a dictionary or a small list, you don't need to build a set 

 for key,value in dict2.items():
    if value in listy:
        print(key)

要么 :

 # If listy is a large list, you should build a set only once 

 listySet = set(listy)
 for key,value in dict2.items():
    if value in listySet:
        print(key)

如果您有很多代码要对“联接”的数据执行,则可以这样构造条件:

 for key,value in dict2.items():
    if value not in listy: continue
    print(key)
    ... do more stuff ...

如果您只想求和,则可以直接进行以下操作:

# counting sum of dict2 keys matching each value in listy  
# select sum(dict2.key) from listy join dict2 where dict2.value = listy.value
# (note that an inverted dict2 would be better suited for that)

result = sum(key*listy.count(value) for key,value in dict2.items())

# counting sum of keys in dict2 that have a value in listy 
# select sum(dict2.key) from dict2 where exists listy.value = dict2.value

result = sum(key for key,value in dict2.items() if value in listy)

简而言之,您必须在SQL中实现RDBMS查询优化器通常为您执行的链接逻辑。

如果您翻转字典中的键和值,您的任务将更加容易。 我假设没有重复的值。

dict2 = {1: "A", 2: "B", 3: "C"}
lookup = {value: key for key, value in dict2.items()}

现在lookup{'A': 1, 'B': 2, 'C': 3} 现在您可以遍历列表:

listy = ['A', 'M', 'B', 'A']
result = []
for key in listy:
    if key in lookup:
        result.append(key)

现在result['A', 'B', 'A'] 具有列表理解的代码将更短:

result = [key for key in listy if key in lookup]

至于我unterstood问题要拿到钥匙的总和dict2在每个条目listy已在相应的值dict2 如果创建了lookup字典,则可以执行以下操作以获取单个值。

[lookup.get(key, 0) for key in listy]
# -> [1, 0, 2, 1]

如果键没有出现在字典中,它将获得默认值0

现在获得总和很容易

sum(lookup.get(key, 0) for key in listy)
# -> 4

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM