Check that exists only one entity in the values of the nested dictionary or not

Viewed 69
people = {1: {'Name': 'John', 'Age': '27', 'Sex': 'Male'},
          2: {'Name': 'Marie', 'Age': '22', 'Sex': 'Female'}}

I have this nested dictionary. I want to print True if all the values of Age will have a similar value. If any one of the values of Age is different, it will print False. Kindly explain how to do it?

4 Answers

You can save the first age and then check other Age is equal to the first or not.

(The first approach with any, when the generator face to an inequality break, so I think the first approach is faster than creating a set of all elements and then checking the length of set)

people = {1: {'Name': 'John', 'Age': '27', 'Sex': 'Male'},
          2: {'Name': 'Marie', 'Age': '22', 'Sex': 'Female'}}

# first approach
first_age = list(people.values())[0]['Age']
if any(dct['Age'] != first_age for dct in people.values()):
    print('different')
else:
    print('equal')

# second approach
# Or check with `set` and check length of `set`
if len(set(dct['Age'] for dct in people.values())) > 1:
    print('different')
else:
    print('equal')

Output:

different

As stated in the comment, you could do:

all_ages_equal = len({d['Age'] for d in people.values()})==1

Grab any dictionary item (here, the first value). Compare all ages to the age of that item using all.

people = {1: {'Name': 'John', 'Age': '27', 'Sex': 'Male'},
          2: {'Name': 'Marie', 'Age': '22', 'Sex': 'Female'}}

v0 = list(people.values())[0]
print(all([v['Age'] == v0['Age'] for v in people.values()]))

Another version, that isn't creating set or list first. It will short-circuit on first difference:

people = {
    1: {"Name": "John", "Age": "27", "Sex": "Male"},
    2: {"Name": "Marie", "Age": "22", "Sex": "Female"},
}

v = iter(people.values())
print(all(a["Age"] == b["Age"] for a, b in zip(v, v)))

Prints:

False
Related