2013-11-27 74 views
0

考慮到與列表字典作爲值和一個單獨的列表:更新列表

myDict = {0: [0, 1, 2], 1: [], 2: [20, 25, 26, 28, 31, 34], 3: [], 4: [0, 1, 2, 3, 4, 7, 10], 5: [], 6: [10, 20, 24]} 

myList = [1, 34, 10] 

如何刪除從列表中值myDict,如果他們匹配myList中值是多少?

所以對於例如字典我期待在年底這樣一個字典:

myDict = {0: [0, 2], 1: [], 2: [20, 25, 26, 28, 31], 3: [], 4: [0, 2, 3, 4, 7], 5: [], 6: [20, 24]} 

回答

2

這工作:

>>> myDict = {0: [0, 1, 2], 1: [], 2: [20, 25, 26, 28, 31, 34], 3: [], 4: [0, 1, 2, 3, 4, 7, 10], 5: [], 6: [10, 20, 24]} 
>>> myList = [1, 34, 10] 
>>> {x:[z for z in y if z not in myList] for x,y in myDict.items()} 
{0: [0, 2], 1: [], 2: [20, 25, 26, 28, 31], 3: [], 4: [0, 2, 3, 4, 7], 5: [], 6: [20, 24]} 
>>> 
3

myList一組,並使用字典和列表理解組合:

mySet = set(myList) 

myDict = {k: [i for i in v if i not in mySet] for k, v in myDict.items()} 

使用一組使得這更高效,因爲in成員測試的集合比列表要快得多。

0

這個答案也行:

updatedDict = {k:list(set(v) - set(myList)) for k, v in myDict.items()}