## faqts : Computers : Programming : Languages : Python : Snippets : Dictionaries

##### + Search
 Did You Find This Entry Useful? 1 of 2 people (50%) answered YesRecently 1 of 2 people (50%) answered Yes

### Entry

##### How can we compare the values of a Dictionar to values of a list?

Jan 23rd, 2008 07:47
stephen brown, Gagandeep Sharma,

You can convert the values of a dictionary to a list with the values()
method:
MyDictValues = MyDict.values()
and reduce the problem to comparing two lists.  They come out in no
particular order (does order matter in your lists?)
There are a lot of different ways to compare two lists, so you have to
be more specific on this point.
Two lists, identical values in identical order:
list1==list2
Values in same position in both lists:
[x for x, y in zip(list1, list2) if x==y]
Values in both lists regardless of position:
[x for x in list1 if x in list2]
Key,value pairs in a dictionary if values appear in list:
[(x, y) for x, y in mydict.iteritems() if y in mylist]
Same returned as a new dictionary:
dict([(x, y) for x, y in mydict.iteritems() if y in mylist])
Examples:
>>> list1 = [1, 2, 3]
>>> list2 = [1, 2, 3]
>>> list3 = [3, 2, 1]
>>> list4 = [3, 4, 5]
>>> [x for x, y in zip(list1, list2) if x==y]
[1, 2, 3]
>>> [x for x, y in zip(list1, list3) if x==y]
[2]
>>> list1==list2
True
>>> list1==list3
False
>>> [x for x in list1 if x in list2]
[1, 2, 3]
>>> [x for x in list1 if x in list3]
[1, 2, 3]
>>> [x for x in list1 if x in list4]
[3]
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> [(x, y) for x, y in mydict.iteritems() if y in list2]
[('a', 1), ('c', 3), ('b', 2)]
>>> [(x, y) for x, y in mydict.iteritems() if y in list3]
[('a', 1), ('c', 3), ('b', 2)]
>>> [(x, y) for x, y in mydict.iteritems() if y in list4]
[('c', 3)]
>>> dict([(x, y) for x, y in mydict.iteritems() if y in list4])
{'c': 3}
>>>