Home > Net >  Getting non equals values from a nested dictionary
Getting non equals values from a nested dictionary

Time:11-04

I've got a nested dictionary like that

my_dict =  {

'ae15': {'selector1fpc0': {'12': ' 3b1874ee5465656256079d02a301acf5'},
          'selector1fpc1': {'12': ' 3b1874ee5465656256079d02a301acf5'},
          'selector1fpc10': {'12': ' 3b1874ee5465656256079d02a301acf5'},
          'selector1fpc4': {'12': ' 3b1874ee5465656256079d02a301acf5'},
          'selector1fpc5': {'12': ' de80451ee5a9e5d69f243a42f1e72d1f'},
          'selector1fpc7': {'12': ' 3b1874ee5465656256079d02a301acf5'},
          'selector1fpc8': {'12': ' 3b1874ee5465656256079d02a301acf5'},
          'selector1fpc9': {'12': ' 3b1874ee5465656256079d02a301acf5'}},
 'ae16': {'selector1fpc0': {'7': ' 119a58e92e581d90eba9a57262d297e5'},
          'selector1fpc1': {'7': ' 119a58e92e581d90eba9a57262d297e5'},
          'selector1fpc10': {'8': ' 119a58e92e581d90eba9a57262d297e5'},
          'selector1fpc4': {'7': ' 119a58e92e581d90eba9a57262d297e5'},
          'selector1fpc5': {'7': ' 119a58e92e581d90eba9a57262d297e5'},
          'selector1fpc7': {'7': ' 119a58e92e581d90eba9a57262d297e5'},
          'selector1fpc8': {'7': ' 119a58e92e581d90eba9a57262d297e5'},
          'selector1fpc9': {'7': ' 119a58e92e581d90eba9a57262d297e5'}}}

and I want to check if all internal values of the dict are equals

i.e

in ae15 selector1fpc5 value is different from the rest however in ae16 all the values are identical

I'm trying the following code

for k, dic in my_dict.items():
    print(dic.values())
    iterable = iter(dic.values())
    first = next(iterable)
    all_equals = all(first == val for val in iterable for k in dic.keys())
    print(k,all_equals)

however I'm getting False in both cases, when actually only ae195 has a different value.

CodePudding user response:

You need to nest one level deeper at a different place:

from itertools import chain

for k, dic in my_dict.items():
    iterable = chain(*(d.values() for d in dic.values())) # to here  ...
    first = next(iterable)
    all_equals = all(first == val for val in iterable)  # ... from here!
    print(k, all_equals)

ae15 False
ae16 True
  • Related