There is such a list containing dictionaries:

list_param = [{'company': 'Apple', 'tariff_rate': Decimal('3.00')}, {'company': 'Apple', 'tariff_rate': Decimal('4.00')}, {'company': 'Apple', 'tariff_rate': Decimal('3.00')}] 

Moreover, companies can be many different, you need to find the same ratio for the same ones.

I have the following:

  def comparison_rate(d, x): k = x['company'] if k in d: d[k]['tariff_rate'] = max(x['tariff_rate'] for k in d) else: d[k] = x return d tariff = reduce(comparison_rate, list_param, {}).values() 

Gives just the latest dictionary, in this case with a factor of 3.0

 print(tariff) [{'tariff_rate': Decimal('3.00'), 'company': 'Apple'}] 

Python 3.5. Thank you in advance.

    1 answer 1

    Error in this line:

     d[k]['tariff_rate'] = max(x['tariff_rate'] for k in d) 

    I didn’t quite understand what you wanted to do here, but the expression in brackets will always contain a certain number of identical elements. Accordingly, to take the maximum from this makes no sense.

    The code will start working if you replace this line with something like:

     d[k]['tariff_rate'] = max(d[k]['tariff_rate'], x['tariff_rate']) 

    But, in general, IMHO, you have overcomplicated. I would solve this problem like this:

     srt = sorted(list_param, key=lambda d: d['tariff_rate']) tariff = {} for dct in srt: tariff.update({dct['company']: dct['tariff_rate']}) print(tariff) 

    UPD: As for the question in the comments.

    The easiest way is to replace the line inside the loop with this:

     tariff.update({dct['company']: dct}) 

    In this case, in the result dictionary, for each company you will have completely the dictionary from the original list, in which the tariff for this company was maximum.

    It will look something like this:

    {'Apple': {'company': 'Apple', 'tariff_rate': Decimal('4.00'), 'sum': 100}}

    Accordingly, after this, you can already by the name of the parameter get from this dictionary at least the tariff, even the sum, at least some other indicator, if it was in the original data:

    tariff['Apple']['sum']

    • Thank! Do not tell me again if I have in the dictionary, besides 'company' and 'tariff_rate', we also say 'sum' is. How can I get this neighboring element - 'sum' from this maximum coefficient? - Fill
    • @Fill, added in response. - Xander
    • You can get it by name, of course, but what if I don’t know in advance which company has the maximum coefficient? I understand you need to go back through the dictionary, which we have updated, find someone max, pull out 'sum'. That is, first found the maximum coefficient. for each company, then among them :) - Fill
    • Added it like this: m = max(tariff, key=lambda i: tariff[i]['tariff_rate']) print(tariff[m]['sum']) - Fill