[Tutor] Test to check if values of dictionary are all equal (which happen to be dictionaries)
Peter Otten
__peter__ at web.de
Sun Nov 9 19:56:12 CET 2014
Jignesh Sutar wrote:
> I needed to test if the values of all entries in a dictionary were equal
> but since the values themselves were dictionaries I couldn't simply take a
> set of the values and test if this equated to one. So I ended up taking
> all combination of the keys and testing pairs of sub dictionaries. I just
> want to check that there isn't a more direct way of doing this that
> testing all combinations?
>
>
> import itertools
>
> dictmain={"K1": {1:"SD_V1",2:"SD_V2"},
> "K2": {1:"SD_V1",2:"SD_V2"},
> "K3": {1:"SD_V1",2:"SD_V2"}}
>
> for compare in list(itertools.combinations(dictmain,2)):
> print "Comparing dictionaries:", compare
>
> if dictmain[compare[0]]==dictmain[compare[1]]:
> print "comb dict are equal"
> else:
> print "comb dict are NOT equal"
> break
>
>
> Many thanks in advance,
> Jignesh
If you don't have exotic data in your dicts equality should be transitive,
i. e. from
a == b and a == c
follows
b == c
so that you don't have to test the latter explicitly.
This reduces the number of tests significantly.
values = dictmain.itervalues() # Python 3: iter(dictmain.values())
first = next(values) # pick an arbitrary value to compare against all others
if all(first == item for item in values):
print("all dicts are equal")
else:
print("not all dicts are equal")
More information about the Tutor
mailing list