Reputation: 189
I have a dict d
d = {'A1': ['Mike', 'Mouse'],
'A2': ['Don', 'Duck'],
'A3': ['Bart','Simp']}
and a list l
l = ['Sar', 'Mike', 'Duck', 'Hox12', 'Bart', '10r']
My goal is to create a new list new_l
that does not have the items in l
e.g. Mike
that are also in d
e.g. 'A1': ['Mike', 'Mouse']
.
I would like my new_l
to be
new_l = ['Sar', 'Hox12', '10r]
I have tried
new_l = []
for k, v in d.items():
if v not in l:
new_l.append(v)
and
new_l = []
for names in l:
if names not in v in d.items():
new_l.append(names)
But they both do not give me my desired output.
How do I change my code to get my desired new_l
?
Upvotes: 0
Views: 30
Reputation: 11
You can also try this one-liner:
new_l = reduce(list.__add__, [list(set(items) - set(l)) for items in d.values()])
Upvotes: 1
Reputation: 412
use extend functionality to prepare a list using dict values.
new_l = []
d = {'A1': ['Mike', 'Mouse'],
'A2': ['Don', 'Duck'],
'A3': ['Bart','Simp']}
l = ['Sar', 'Mike', 'Duck', 'Hox12', 'Bart', '10r']
to_cmp_l = []
for k,v in d.items():
to_cmp_l.extend(v)
for item in l:
if item not in to_cmp_l:
new_l.append(item)
print(new_l)
Upvotes: 1
Reputation: 728
s = set()
for v in d.values():
s |= set(v)
new_l = [e in l if e not in s]
convert each value to set and build a set of all values in the dictionary. Build the new list by checking for membership in the set.
You could use a list instead of a set, though a set has certain advantages, namely that elements are unique and the membership test is a constant time operation.
|=
is shorthand for adding elements to an existing set. Docs
Upvotes: 1