Get the lowest value with the map in a Dict

Asked

Viewed 54 times

-2

I’m studying the function map() And I was wondering if there’s any way I could retrieve the least value from a dictionary within a list. The way I’m doing I’m only managing to change all values.

arroz = [
{'item': 'arroz', 'preco': 20.15, 'mercado': 'mercado_1'},
{'item': 'arroz', 'preco': 19.99, 'mercado': 'mercado_2'},
{'item': 'arroz', 'preco': 22.00, 'mercado': 'mercado_3'},
{'item': 'arroz', 'preco': 17.99, 'mercado': 'mercado_4'}]


def menorpreco(arroz, valor):
    def item(p):
        p['preco'] = valor
        return p
    return map(item, arroz)


print(list(menorpreco(arroz, 10)))

1 answer

1


The function item is modifying the price value because you do p['preco'] = valor, then it doesn’t seem to be what you need.

Moreover, map serves to apply a function to all elements of an iterable, returning the results of this function (in case, it is using the function item, that changes prices, so the return has changed prices).

If you want to fetch the lowest price, use min:

def menorpreco(arroz):
    return min(arroz, key=lambda d : d['preco'])

arroz = [
{'item': 'arroz', 'preco': 20.15, 'mercado': 'mercado_1'},
{'item': 'arroz', 'preco': 19.99, 'mercado': 'mercado_2'},
{'item': 'arroz', 'preco': 22.00, 'mercado': 'mercado_3'},
{'item': 'arroz', 'preco': 17.99, 'mercado': 'mercado_4'}]

mais_barato = menorpreco(arroz)
print(mais_barato) # {'item': 'arroz', 'preco': 17.99, 'mercado': 'mercado_4'}

The parameter key indicates which value will be used in comparison, and in case I used the price.

The return is the entire dictionary that contains the lowest price. But if you just want the value, just do mais_barato['preco'].


But in case of a tie (has more than one item that is the cheapest), you can return a list with the cheapest items:

def menorpreco(arroz):
    # primeiro vê qual o menor preço
    menor_preco = min(arroz, key=lambda d : d['preco'])['preco']
    # retorna uma lista com todos os itens cujo preço é igual ao menor_preco
    return [ item for item in arroz if item['preco'] == menor_preco]

arroz = [
{'item': 'arroz', 'preco': 20.15, 'mercado': 'mercado_1'},
{'item': 'arroz', 'preco': 17.99, 'mercado': 'mercado_5'},
{'item': 'arroz', 'preco': 19.99, 'mercado': 'mercado_2'},
{'item': 'arroz', 'preco': 22.00, 'mercado': 'mercado_3'},
{'item': 'arroz', 'preco': 17.99, 'mercado': 'mercado_4'}]

print(menorpreco(arroz)) # [{'item': 'arroz', 'preco': 17.99, 'mercado': 'mercado_5'}, {'item': 'arroz', 'preco': 17.99, 'mercado': 'mercado_4'}]
  • Thank you. helped me and a lot in understanding. vlw

Browser other questions tagged

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