ustroetz
ustroetz

Reputation: 6292

Update lists in dictionary based on another list

Given a dictionary with lists as values and a seperate list:

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]

How can I remove values from the lists in myDict, if they match the values in myList?

So for the example dictionary I expect in the end a dictionary like this:

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

Upvotes: 0

Views: 69

Answers (3)

itdxer
itdxer

Reputation: 1256

This answer also work:

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

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121446

Make myList a set, and use a dict and list comprehension combo:

mySet = set(myList)

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

Using a set makes this more efficient, as the in membership test is a lot faster for sets than it is for lists.

Upvotes: 3

user2555451
user2555451

Reputation:

This works:

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

Upvotes: 2

Related Questions