开发者

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?


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])


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜