简体   繁体   中英

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.

So far, I can't join the two, I've tried using get and set and am not succeeding.

I also tried a for loop with set linking listy and dict2, like this:

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:

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

Also your dictionary's entries contain single values (not lists) so you can use the in operator:

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.

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} . 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'] . 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 . If you have created the lookup dictionary you can do the following to get the single values.

[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 .

To get the sum is easy now

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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