Greenseed
Greenseed

Reputation: 39

Default Dict / Sort by min

and thank you in advance for your help. I have this code so far :

with open("clean_result.csv", "r", encoding="utf-8", errors="ignore") as 
new_data:
reader = csv.reader(new_data, delimiter=',', quotechar='"')
for row in reader:
    if row:
        columns = [row[0], row[1]]
        init_dict.append(columns)

for ean, price in init_dict:
    result[ean].append(price)

And then I get the min value for each price with this line :

maxitems = {ean : min(result[ean]) for ean in result}

Current Output : {'8714789828558': '5,51', '3326100000182': '15,00', '3286010016683': '3,93' (...) }


What I would like to is add row[2] and get additionnal info, but only for the minimum price value.

Desired Output : {'8714789828558': '5,51', 'A', '3326100000182': '15,00', 'B' '3286010016683': '3,93', 'C' (...) }

I tried this :

for row in reader:
    if row:
        columns = [row[0], row[1], row[2]]
        init_dict.append(columns)

for ean, price, desc in init_dict:
       result[ean].append(price)
       result[ean].append(desc)

maxitems = {ean : min(result[ean]) for ean in result}

But Output is like this. Half data are missing :

{'8714789828558': 'A', '3326100000182': 'B' '3286010016683': 'C' (...) }

I probably misunderstand something so please any help appreciated

Upvotes: 2

Views: 107

Answers (1)

khachik
khachik

Reputation: 28703

from operator import itemgetter
from collections import defaultdict

result = defaultdict(list)

for row in reader:
    if row:
        result[row[0]].append((row[1], row[2]))

minitems = {ean : min(prices, key = itemgetter(0)) for ean, prices in result.iteritems()}

Upvotes: 1

Related Questions