Reputation: 129
I have list and dictionary like this:
list_1 = ['if looks kill then i'm murdering]
dic_1 = {"kill": -2, "murdering": -3}
I want to extract list items that matches the dictionary key and append it to a set. I have two problems: 1. I cannot extract the list items that matches with key in the dictionary 2. How do I append list items to a set?
set_1 = set()
for items in list_1:
list_1 = items.lower().split()
for term in dic_1:
forth_list = [words for words in list_1 if term != words]
print forth_list
['if', 'looks', 'then', 'i', 'm', 'murdering']
['if', 'looks', 'kill', 'then', 'i', 'm']
set_1.add(forth_list) # this produce a TypeError: unhashable type: 'list'
print set_1
Upvotes: 1
Views: 170
Reputation: 1121486
The most efficient way to find what elements in the list are in a dictionary, is to use dictionary views:
set_1 |= dic_1.viewkeys() & list_1
A dictionary view such as returned by dic_1.viewkeys()
is essentially a set, and by using &
we take the intersection of that set and the list.
The |=
syntax, using in-place OR, updates the set to add any elements found in the right-hand side not yet in the set.
Alternatively, you could use the set.update()
method. The .add()
method takes one element at a time instead, but you wanted to add all elements in the list to the set, not the list itself.
Demo:
>>> list_1 = "if looks kill then i'm murdering".split()
>>> dic_1 = {"kill": -2, "murdering": -3, "monty": 5}
>>> set_1 = set()
>>> set_1 |= dic_1.viewkeys() & list_1
>>> set_1
set(['murdering', 'kill'])
>>> set_1 |= dic_1.viewkeys() & "monty python's flying circus".split()
>>> set_1
set(['murdering', 'kill', 'monty'])
Upvotes: 7
Reputation: 36767
The direct pythonic one-liner translation of what you're describing is:
set_1 = set(val for val in list_1.split() if val in dic_1)
It takes each value from the split, checks if that value is a key in dictionary and constructs a set out of those values using a generator expression.
Upvotes: 3