У меня есть код, который читает CSV и создает словарь с муниципалитетом в качестве ключа и списком классификации земельного покрова и его площадью в качестве значения:

with open (file) as f:
    csvreader = csv.reader(f)
    for row in csvreader:
        result[row[1]].append(row[0])
        result[row[1]].append(row[2])
    print(result)

Результат 1 - NAME_2 ': [' DESCRIPT ',' area ']

{'Cabusao': ['Crop land mixed with coconut plantation', '6446690.72729492', 'Coconut plantations', '156914.753356934', 'Cultivated Area mixed with brushland/grassland', '4356221.33416748', 'Arable land, crops mainly cereals and sugar', '11530447.4974976', 'Crop land mixed with coconut plantation', '5975853.80914307', 'Coconut plantations', '9898.44506835938', 'Coconut plantations', '1389881.81445313'], ...}

Добавление этого цикла for группирует элементы в списке, но не добавляет значения (сохраняет только одно из них) и помещает каждый результат в отдельный словарь.

for i in result:
    d = dict(itertools.zip_longest(*[iter(result[i])] * 2, fillvalue=""))
    print(d)

Результат 2 - {'DESCRIPT': 'area'}

{'Crop land mixed with coconut plantation': '5975853.80914307', 'Coconut plantations': '1389881.81445313', 'Cultivated Area mixed with brushland/grassland': '4356221.33416748', 'Arable land, crops mainly cereals and sugar': '11530447.4974976'}

Итак, как мне получить результат, аналогичный Результату 1, но элементы в списке сгруппированы по ключу, а значения суммированы? Здесь суммированы посевные площади и кокосовые плантации.

{'Cabusao': ['Crop land mixed with coconut plantation':'12,422,544.53643799', 'Coconut plantations', '1,556,695.012878423', 'Cultivated Area mixed with brushland/grassland', '4356221.33416748', 'Arable land, crops mainly cereals and sugar', '11530447.4974976'], ...}
1
BallpenMan 25 Июн 2020 в 11:50

1 ответ

Лучший ответ

IIUC, если предположить, что d - это первый опубликованный вами словарь,

ans = {}; new_dict = {} 
for key,sub_list in d.items(): 
    for idx in range(0, len(sub_list), 2): 
         if sub_list[idx] not in new_dict:
             new_dict[sub_list[idx]] = float(sub_list[idx+1]) 
         new_dict[sub_list[idx]] += float(sub_list[idx+1]) 
     ans[key] = new_dict

О / р

{'Cabusao': {'Crop land mixed with coconut plantation': 12422544.53643799,
  'Coconut plantations': 1556695.0128784233,
  'Cultivated Area mixed with brushland/grassland': 4356221.33416748,
  'Arable land, crops mainly cereals and sugar': 11530447.4974976}
}
1
Aditya 25 Июн 2020 в 09:09