Reputation: 77
I have a Python set
A = {34, 4, 7, 39, 40, 13, 18, 20}
and a dictionary
B = {4: [6, 34, 39], 7: [18, 34], 13: [6, 18, 34], 18: [7, 13],
20: [31, 47], 34: [4, 7, 13], 39: [4, 8], 40: [15, 43]}
I want to create a new dictionary C such that if any of the values in B contains a number in A, then they must be removed from the corresponding value list. Keys should be unaffected.
For example, the desired output that I am looking for is:
C = {4: [6], 7: [], 13: [6], 18: [], 20: [31, 47], 34: [], 39: [8]}
I tried to solve this using the following code:
C = {}
for key, value in B_mod.items():
if value in A:
C[key] = value
print("C is:", C)
The output that I am getting is as follows:
C is: {7: 18, 18: 7, 34: 4, 39: 4}
Clearly, it is not working.
*Please note that B_mod
means that I am unlisting the list in values of dictionary B using the code:
B_mod = {k:v[0] for k,v in B.items()} # Unlisitng the values of dictionary B
I did this because I could not iterate through lists as values in B.*
Any help to get C?
Upvotes: 1
Views: 68
Reputation: 1737
You can do it in one line with this dictionary and list comprehension:
C = {k: [x for x in v if x not in A] for k, v in B.items()}
Upvotes: 1
Reputation: 59315
You can use a combination of a dictionary and list comprehensions:
>>> {k: [i for i in v if i not in A] for k, v in B.items()}
{4: [6], 7: [], 13: [6], 18: [], 20: [31, 47], 34: [], 39: [8], 40: [15, 43]}
Upvotes: 1
Reputation: 96172
You definitely can iterate through the lists in the values of B
, indeed, you need to, so something like this:
>>> A = {34, 4, 7, 39, 40, 13, 18, 20}
>>> B = {4: [6, 34, 39], 7: [18, 34], 13: [6, 18, 34], 18: [7, 13], 20: [31, 47], 34: [4, 7, 13], 39: [4, 8], 40: [15, 43]}
>>> C = {}
>>> for key, value in B.items():
... new_value = []
... for val in value:
... if val not in A:
... new_value.append(val)
... C[key] = new_value
...
>>> C
{4: [6], 7: [], 13: [6], 18: [], 20: [31, 47], 34: [], 39: [8], 40: [15, 43]}
>>>
You can also use a dictionary comprehension with a list comprehension:
>>> {k:[v for v in vs if v not in A] for k, vs in B.items()}
{4: [6], 7: [], 13: [6], 18: [], 20: [31, 47], 34: [], 39: [8], 40: [15, 43]}
Which is the equivalent of the for-loop approach. Whichever makes more sense to you is fine.
Upvotes: 2