Browse and collect data from dictionaries within a list

Asked

Viewed 53 times

1

I have a list of several dictionaries containing registration data:

[{'sex': ’M', 'age': 44}, {'sex': 'F', 'age': 33}, {'sex': ’M', 'age': 55}]

I created separate functions to calculate the average, and the number of female/male people (and also the percentage)

But my problem is in passing the parameter to these functions, and how to go through this list to collect the data (for example, a repeat structure to collect the 'age' data to calculate the average.), as I would do this access?

2 answers

2


You can do it in several ways, for example you could package this data in a class but as you said already have separate functions a simple way to do it is like this:

meus_dados = [
    {'sexo': 'M', 'idade': 44},
    {'sexo': 'F', 'idade': 33},
    {'sexo': 'M', 'idade': 55}
]

def media(dados):

    total, itens = 0, 0

    for item in dados:
        valor = item.get('idade', 0)
        if valor:
            itens += 1
            total += valor

    return (total / itens) if itens else 0


print(media(meus_dados))

You can send the full list to the function, then scan element by element (the for) using the method .get() to recover the value of the key you seek* and finding you perform the operation.

Note that my code only sums the ages if they exist, if the increment of itens should be outside the if ....

(*) the second parameter is the default value if there is no key, see the documentation for more information).

  • Ah, in Python 3.8 onwards you can use the operator Walrus and just do if valor := item.get('idade', 0): ...

1

Another approach would be to use reduce:

import functools 

dados = [{'sexo': 'M', 'idade': 44}, {'sexo': 'F', 'idade': 33}, {'sexo': 'M', 'idade': 55}]

def reduzir(anterior, atual):
  anterior[atual['sexo']]['qtde'] += 1
  anterior[atual['sexo']]['idade'] += atual['idade']
  return anterior

base = { 'M': { 'idade': 0, 'qtde': 0 }, 'F': { 'idade': 0, 'qtde': 0 } }
functools.reduce(reduzir, dados, base)

The result is:

{'F': {'idade': 33, 'qtde': 1}, 'M': {'idade': 99, 'qtde': 2}}

This way you have the result separated by sex, being able to average by sex or general.

Browser other questions tagged

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