user256858
user256858

Reputation: 15

Python List Exclusions

I have a dictionary of lists with info such as var1=vara, var1=varb, var2=vara etc. This can have lots of entries, and I print it out ok like this

for y in myDict:  
    print(y+"\t"+myDict[y])

I have another list which has exclusions in like this var2, var3 etc. This may have < 10 entries and I can print that ok like this

for x in myList:
    print(x)

Now I want to remove occurrences of key val pairs in the dictionary where the keys are the list values. I tried this

for x in myList:
    for y in myDict:
        if x != y: print(y+"\t"+myDict[y])

but on each pass through the list it lets all the others apart from the current `x to the screen

Is there a nice python way to remove the key val pairs from the dictionary if the key exists in the list?

Upvotes: 0

Views: 266

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799420

mySet = set(myList)
myNewDict = dict(((k, v) for k, v in myDict if k not in mySet))

Note that using mySet instead of myList isn't a concern unless myList has a large number of entries.

Upvotes: 1

Jochen Ritzel
Jochen Ritzel

Reputation: 107746

Do you mean

for key in myDict:
    if key not in myList:
        print(key+"\t"+myDict[key])

Or one of many alternatives:

for key in (set(myDict)-set(myList)):
    print(key+"\t"+myDict[key])

Upvotes: 5

Related Questions