user690462
user690462

Reputation: 129

How can I extract list items using dictionary keys?

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

This will print

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

Answers (2)

Martijn Pieters
Martijn Pieters

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

soulcheck
soulcheck

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

Related Questions