dNm
dNm

Reputation: 23

Python - intersection between list and dict keys

I have this list:

list1 = [{'Hello'}, {'Welcome'}, {'BYE'}]

And I have a dictionary:

dict1 = {'Welcome': 5, 'BYE': 3, 'How are you': 3}

I would like the result to be something like:

dict2 = {'Welcome': 5, 'BYE': 3}

According to this post. I tried:

dict2 = {k: dict1[k] for k in (dict1.keys() & list1)}

But it says:

TypeError: unhashable type: 'set'

Do I need first to make list1, like this:

list1 = ['Hello', 'Welcome', 'BYE']

And if this is the problem, then how?

Upvotes: 1

Views: 260

Answers (3)

Godwinh19
Godwinh19

Reputation: 86

Yes your variable list1 is a list of set, you might do this:

dict2 = {k: dict1[k] for k in set(dict1.keys()).intersection(set().union(*list1))}

Upvotes: 1

deceze
deceze

Reputation: 522091

If you are required to start with that weird single-item-set-in-list list, I'd flatten it with itertools.chain.from_iterable into a simple list. From there, with a simple dictionary comprehension, you create a new dictionary for each key from list1 that exists in dict1:

>>> from itertools import chain
>>> list1 = [{'Hello'}, {'Welcome'}, {'BYE'}]
>>> dict1 = {'Welcome': 5, 'BYE': 3, 'How are you': 3}
>>> list(chain.from_iterable(list1))
['Hello', 'Welcome', 'BYE']
>>> {k: dict1[k] for k in chain.from_iterable(list1) if k in dict1}
{'Welcome': 5, 'BYE': 3}

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195438

You can make a set of value from the list1:

list1 = [{"Hello"}, {"Welcome"}, {"BYE"}]
dict1 = {"Welcome": 5, "BYE": 3, "How are you": 3}


dict2 = {k: dict1[k] for k in (dict1.keys() & {v for s in list1 for v in s})}
print(dict2)

Prints:

{'BYE': 3, 'Welcome': 5}

Upvotes: 2

Related Questions