Passing dictionaries key as parameter in integrated function

Asked

Viewed 35 times

1

I have a simple question about using working dictionaries. Is there any way I can pass the values of the ["Age"] keys of the dictionaries in the abc list as a parameter in the Mean function? (average a list)

import statistics as stt
abc = [{"Nome": "Joana", "Idade": 14}, {"Nome": "Fernanda", "Idade": 24}, {"Nome": "Josué", "Idade": 24}]
###abc = [2, 4, 3, 5, 5, 3, 44, 5, 3]
stt.mean(abc)

1 answer

3


You can use the function map to map the list with the dictionaries in a list with only the ages and then calculate the average.

import statistics as stt

pessoas = [{"Nome": "Joana", "Idade": 14},
           {"Nome": "Fernanda", "Idade": 24},
           {"Nome": "Josué", "Idade": 24}]

idades = map(lambda pessoa: pessoa['Idade'], pessoas)
avg = stt.mean(idades)

print(f"A média é: {avg}.")

In the code above, we passed to the map one lambda Function, that accesses (and returns) the dictionary age of each mapping iteration.

Another option (to map with lambda) is to use list comprehensions:

idades = [pessoa['Idade'] for pessoa in pessoas]
avg = mean(idades)

The output, for both codes, will be the same:

A média é: 20.666666666666668.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.