How do you compare an item with all other items in the same list (with dictionaries inside) in a pythonic way?

Asked

Viewed 63 times

0

I’m a beginner, guys. Just for the record!

I am trying to compare the items on a list with dictionaries and if they are equal, add these items. I think with one example, the idea becomes clearer:

dados = [
        {"Codigo": 1, "Valor": 300.00,},
        {"Codigo": 1, "Valor": 300.00,},
        {"Codigo": 2, "Valor": 400.00,},
        {"Codigo": 1, "Valor": 300.00,},
        {"Codigo": 2, "Valor": 400.00,},
        {"Codigo": 2, "Valor": 400.00,}
]

print(f'Número de itens: {len(dados)}')

for dado in dados:
    print(f"{dado['Codigo']} = {dado['Valor']}")

The question is: If the values of Codigo are equal - How to sum these values in an item and return only the total sum?

Thank you for your attention!

2 answers

2


If the intention is only pedagogical you can make a group by 'manual', and go adding:

dados = [
        {"Codigo": 1, "Valor": 300.00,},
        {"Codigo": 1, "Valor": 300.00,},
        {"Codigo": 2, "Valor": 400.00,},
        {"Codigo": 1, "Valor": 300.00,},
        {"Codigo": 2, "Valor": 400.00,},
        {"Codigo": 2, "Valor": 400.00,}
]

dados_grouped = {}
for d in dados:
    dados_grouped[d['Codigo']] = dados_grouped.get(d['Codigo'], 0) + d['Valor']

Output of data_grouped:

{1: 900.0, 2: 1200.0}

Get function()


For serious things you can use pandas:
import pandas as pd
df = pd.DataFrame(dados)
dados_grouped = df.groupby('Codigo', as_index=False).sum().to_dict('records')

Output of data_grouped:

[{'Codigo': 1.0, 'Valor': 900.0}, {'Codigo': 2.0, 'Valor': 1200.0}]

But it’s important to know that there are other ways to do this in python.

  • 1

    Thank you for coming back, Miguel. The intention is pedagogical. I’m studying lists and dictionaries in Python and trying to increase the difficulty level of the exercises to fix learning. I tried to do with the enumerate (I think that’s the name), but he added and replicated my added values (I made a mistake in the logic of the condition). Anyway, I’ll study what you sent me, okay? Thanks!

  • 1

    @Mmelo, enumerate is unnecessary for this purpose. Good studies

-2

Stop to think... you need to go through a list and add up the values of keys already found, correct?

So you need to somehow, during the list iteration add the values by keys.

So it’s clear that you need to have a new data structure to store these added values during iteration.

For this you can use a key/value structure(hashmap) and after executing the sums, you read this new structure and transform in the new list with the added values.

I’ll do it in JS because I don’t know Python. And I see that this is a lack of knowledge in data structure concepts and basic programming than a doubt about Python actually

const lista = [
  {"Codigo": 1, "Valor": 300.00},
  {"Codigo": 1, "Valor": 300.00},
  {"Codigo": 2, "Valor": 400.00},
  {"Codigo": 1, "Valor": 300.00},
  {"Codigo": 2, "Valor": 400.00},
  {"Codigo": 2, "Valor": 400.00}
];

const tempHashMap = {};

for (item of lista) {
  if (tempHashMap[item.Codigo] != null) {
    tempHashMap[item.Codigo] = tempHashMap[item.Codigo] + item.Valor;
  } else {
    tempHashMap[item.Codigo] = item.Valor
  }
}

const chavesDoHashMap = Object.keys(tempHashMap);

const novaLista = [];

for (chave of chavesDoHashMap) {
  novaLista.push({
    Codigo: chave,
    Valor: tempHashMap[chave]
  });
}

for (item of novaLista) {
  console.log(`${item.Codigo} = ${item.Valor}`)
}

Browser other questions tagged

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