-2

I have a dictionary whose keys are strings and values are numbers. I have another list of strings. I want to filter the dictionary by removing all key, value pairs if the key is a string in the list of string.

So for example: dict={"good":44,"excellent":33,"wonderful":55}, randomList=["good","amazing","great"] Then the method should give newdict={"excellent":33,"wonderful":55}

I'm wondering if there is a way to do it using very little codes. Is there a way to do it fast?

user42493
  • 813
  • 4
  • 14
  • 34

2 Answers2

1

This simple piece of code does what you want

oldDict={"good":44,"excellent":33,"wonderful":55}

randomList=["good","amazing","great"]

for word in randomList:
    if word in oldDict:
        oldDict.pop(word)

print(oldDict)

newDict = oldDict # Optional: If you want to assign it to a new dictionary
# But either way this code does what you want in place

Waqar Bin Kalim
  • 321
  • 1
  • 7
  • 2
    Just a headsup, `newDict = oldDict` won't copy your dictionary. They will both end up being the exact same, and changing one of them will change both. – SyntaxVoid Oct 19 '19 at 01:25
  • Lol yeah, my bad, I forgot about that, and I think it's possible to deep copy it though if the module `copy` is imported, then `newDict = copy.deepcopy(oldDict)`, right? But no, you're right, that was my bad – Waqar Bin Kalim Oct 19 '19 at 01:31
0

Iterate through the dictionary and remove key-value pairs that aren't in the list:

d = {'foo': 0, 'bar': 1, 'foobar': 2}
list_of_str = ['foo', 'bang']
{k:v for k, v in d.items() if k not in list_of_str}

Output:

Out[34]: {'bar': 1, 'foobar': 2}

or if your list_of_str is smaller this would be faster:

d = {'foo': 0, 'bar': 1, 'foobar': 2}
list_of_str = ['foo', 'bang']
for s in list_of_str:
    try:
        del d[s]
    except KeyError:
        pass

Output:

Out[41]: {'bar': 1, 'foobar': 2}
cosmic_inquiry
  • 2,557
  • 11
  • 23