Reputation: 82
What is the fastest way to compare a list and the dict.values in python? Like for example take these two for instance:
dict = {1:'value1', 2:'value2', 3:'value3'}
list = ['val1', 'val2', 'value3']
value3 is there in both datastructures, so what would be the fastest way to go through both of them and return the value3. I've tried using forloops but it's too slow.
Edit: The Dict is dynamic so every time the code runs the values keep on changing and I get an error like this:
unhashable type: 'set'
Upvotes: 1
Views: 227
Reputation: 17322
if you do not want to use sets you can use a list comprehension:
my_dict = {1:'value1', 2:'value2', 3:'value3'}
my_list = ['val1', 'val2', 'value3']
common = [e for e in my_list if e in my_dict.values()]
# ['value3']
Upvotes: 1
Reputation: 54148
Use set()
and get the intersection of both ones, also don't use built-in names dict
and list
for your variables, one day it'll cause you trouble
dict_values = {1:'value1', 2:'value2', 3:'value3'}
list_values = ['val1', 'val2', 'value3']
intersec = set(list_values).intersection(dict_values.values())
print(intersec)
Without set
intersec=[]
for value in dict_values.values():
if value in list_values:
intersec.append(value)
Upvotes: 3