简体   繁体   English

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

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

I am trying to join a list to a dictionary in Python 3 and return the sum of the key values. 我试图在Python 3中将列表加入字典,并返回键值的总和。

So far, I can't join the two, I've tried using get and set and am not succeeding. 到目前为止,我还不能加入两者,我已经尝试使用getset并没有成功。

I also tried a for loop with set linking listy and dict2, like this: 我还尝试了将链接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)

This is the error I'm getting in IPython: 这是我在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'

You can use a list-comprehension: 您可以使用列表理解:

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

In code : 在代码中

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

You probably meant to use dict[k] instead of dict2[value] 您可能打算使用dict[k]而不是dict2[value]

Also your dictionary's entries contain single values (not lists) so you can use the in operator: 另外,词典的条目包含单个值(不是列表),因此您可以使用in运算符:

for example: 例如:

 # 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)

or : 要么 :

 # 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)

If you have a lot of code to perform on the "joined" data, you could structure the condition like this: 如果您有很多代码要对“联接”的数据执行,则可以这样构造条件:

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

If you're only looking for a sum, you can do it more directly: 如果您只想求和,则可以直接进行以下操作:

# 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)

In short, you have to implement the linking logic that the RDBMS query optimizer normally does for you in SQL. 简而言之,您必须在SQL中实现RDBMS查询优化器通常为您执行的链接逻辑。

Your task will be easier if you flip the keys and values in your dictionary. 如果您翻转字典中的键和值,您的任务将更加容易。 I assume that there are no duplicate values. 我假设没有重复的值。

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

Now lookup is {'A': 1, 'B': 2, 'C': 3} . 现在lookup{'A': 1, 'B': 2, 'C': 3} Now you can loop over the list: 现在您可以遍历列表:

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

Now result is ['A', 'B', 'A'] . 现在result['A', 'B', 'A'] The code will be shorter with a list comprehension: 具有列表理解的代码将更短:

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

As far as I unterstood the question you want to get the sum of the keys in dict2 for every entry in listy that has a corresponding value in dict2 . 至于我unterstood问题要拿到钥匙的总和dict2在每个条目listy已在相应的值dict2 If you have created the lookup dictionary you can do the following to get the single values. 如果创建了lookup字典,则可以执行以下操作以获取单个值。

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

If a key doesn't appear in the dictionary it gets a default value of 0 . 如果键没有出现在字典中,它将获得默认值0

To get the sum is easy now 现在获得总和很容易

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

暂无
暂无

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

相关问题 如何加入嵌套Python字典的值? - How do I join the values of nested Python dictionary? 以列表为值的 Python 字典:如何选择值? - Python dictionary with list as values: how do I select values? Python 3-如何列出字典中的前5个值? - Python 3 - how do I list the first 5 values from a dictionary? 给定一个字典,其中值可能是不同的类型,如何将python字典简洁地转换为元组列表? - How do I concisely convert a python dictionary to a list of tuples, given a dictionary in which the values may be different types? 在 Python 中,给定一个包含值列表的字典,如何根据该列表中的项目数量对字典进行排序? - In Python, given a dictionary with lists in the values, how do I sort the dictionary based on the amount of items in that list? 如何将列表作为新项目加入列表字典-python? - How do you join a list to a dictionary of lists as a new item - python? 如何在python的列表中列出在字典中找到的certian值的出现? - How do I list occurrences of certian values found in a dictionary in a list in python? 如何将字典中的值列表更改为一组值? - How do i change a list of values in a dictionary to a set of values? 如何将具有多个值的列表转换成只有2个值的字典? - How do i turn a list with multiple values into a dictionary with only 2 values? 如何对键进行排序:按列表中的值列出字典? - How do I sort a key:list dictionary by values in list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM