Test if all values of a dictionary are equal - when value is unknown

Viewed 9675

I have 2 dictionaries: the values in each dictionary should all be equal.
BUT I don't know what that number will be...

dict1 = {'xx':A, 'yy':A, 'zz':A}
dict2 = {'xx':B, 'yy':B, 'zz':B}

N.B. A does not equal B
N.B. Both A and B are actually strings of decimal numbers (e.g. '-2.304998') as they have been extracted from a text file

I want to create another dictionary - that effectively summarises this data - but only if all the values in each dictionary are the same.
i.e.

summary = {}
if dict1['xx'] == dict1['yy'] == dict1['zz']:
    summary['s'] = dict1['xx']
if dict2['xx'] == dict2['yy'] == dict2['zz']:
    summary['hf'] = dict2['xx']

Is there a neat way of doing this in one line?

I know it is possible to create a dictionary using comprehensions
summary = {k:v for (k,v) in zip(iterable1, iterable2)}
but am struggling with both the underlying for loop and the if statement...

Some advice would be appreciated.

I have seen this question, but the answers all seem to rely on already knowing the value being tested (i.e. are all the entries in the dictionary equal to a known number) - unless I am missing something.

5 Answers

I found this solution, which I find quite a bit I combined another solution found here: enter link description here

user_min = {'test':1,'test2':2}
all(value == list(user_min.values())[0] for value in user_min.values())

>>> user_min = {'test':1,'test2':2}
>>> all(value == list(user_min.values())[0] for value in user_min.values())
False
>>> user_min = {'test':2,'test2':2}
>>> all(value == list(user_min.values())[0] for value in user_min.values())
True
>>> user_min = {'test':'A','test2':'B'}
>>> all(value == list(user_min.values())[0] for value in user_min.values())
False
>>> user_min = {'test':'A','test2':'A'}
>>> all(value == list(user_min.values())[0] for value in user_min.values())
True

Good for a small dictionary, but I'm not sure about a large dictionary, since we get all the values to choose the first one

Related