Home > OS >  How to access the same subkey in every key on a nested dictionary?
How to access the same subkey in every key on a nested dictionary?

Time:04-20

I'm new to coding (either in english, so sorry if I misspell) and I got curious about a dictionary funcionality. To be more clear let me give an example:

dictionary = {"person_1": {"city": _, "age": 18}
              "person_2": {"city": _, "age": 25}
              "person_3": {"city": _, "age": 57}
               ...}

I would like to know if there is someway to access every "city" or "age" (maybe to sum ages or something). I thought about a loop however do it at once without having to acess every person would be more efficient. Any help ?

CodePudding user response:

Here's an example of how you could sum all 'ages' in a dictionary with the structure shown in the question:

_ = 'Rio de Janeiro'

dictionary = {"person_1": {"city": _, "age": 18},
              "person_2": {"city": _, "age": 25},
              "person_3": {"city": _, "age": 57}}

sum_of_ages = sum(d['age'] for d in dictionary.values())

print(sum_of_ages)

Output:

100

CodePudding user response:

d1 = {"person_1": {"city": 'LA', "age": 18},
              "person_2": {"city": 'SD', "age": 25},
              "person_3": {"city": 'NY', "age": 57},
             }

Traditional way:

_sum =0
for p in d1.values():
    _sum =p['age']

_sum: 100

List comprehension:

_sum2 = sum([p['age'] for p in d1.values()])

_sum2: 100

CodePudding user response:

yes, dictionaries have a .values() method, let me show you an example:

here i have a dictionaries of cities:

{"city1":{"name":"Italy"}
 "city2":{"name":"United States"}}

to get the list where i have only the names, you can use .values(),turn it into a list since DictValues instances are immutable

so in your case:

dictionary = {"person_1": {"city": "Washington DC", "age": 18}
          "person_2": {"city": "Rome", "age": 25}
          "person_3": {"city": "Berlin", "age": 57}
}

values=list(dictionary.values())
print("values:",values)

output:

values: [{'city': 'Washington DC', 'age': 18}, {'city': 'Rome', 'age': 25}, {'city': 'Berlin', 'age': 57}]

to do the sum of the ages, without loops you could use the map function to get all the ages and then, do the sum with the sum function

dictionary = {"person_1": {"city": "Washington DC", "age": 18}
          "person_2": {"city": "Rome", "age": 25}
          "person_3": {"city": "Berlin", "age": 57}
}
ages=list(map(lambda x:x["age"],dictionary.values()))
sumofages=sum(ages)
print("sum of ages:",sumofages)

output:

sum of ages: 100
  • Related