如何为文件中的键向字典中的键添加值?Python

2024-03-29 00:32:47 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个csv文件,从中我必须找到所有产品的平均价格按类别分组。我设法把文件中的所有行都列成一个列表。 现在我试着这样做:

FILE_NAME = 'catalog_sample.csv'
full_catalog = []

with open(FILE_NAME, encoding='utf-8') as file:
    for line in file:            
        one_record = line.split(',')
        full_catalog.append(one_record)

category_dict = {}
prices = []

for i in full_catalog:
    if str(i[-2]) not in category_dict:
        category_name = str(i[-2])
        category_dict[category_name] = float(i[-1])
    else:
        prices.append(float(i[-1]))

到目前为止,我得到了一个字典,其中包含文件中的所有类别作为键,但值是文件中第一次出现键的价格:

'Men': 163.99
'Women': 543.99

似乎“else”没有像我期望的那样工作(向键添加值)。有什么建议吗?谢谢!你知道吗


Tags: 文件csvnameinforlinerecord类别
1条回答
网友
1楼 · 发布于 2024-03-29 00:32:47

我建议您在浏览文件时创建字典,而不是将它们添加到列表中,然后再重新浏览以构建字典。你知道吗

category_dict = {}
full_catalog = []

with open(FILE_NAME, encoding='utf-8') as file:
    for line in file:
        item = line.split(',')
        # Unpack the last 2 items from list
        category = item[-2].strip()
        price = float(item[-1])

        # Try get the list of prices for the category
        # If there is no key matching category in dict
        # Then return an empty list
        prices = category_dict.get(category, [])
        # Append the price to the list
        prices.append(price)

        # Set the list as the value for the category
        # If there was no key then a key is created
        # The value is the list with the new price
        category_dict[category] = prices
        full_catalog.append(item)

编辑:固定为匹配提供的行格式。 full_catalog如果您仍然需要整个列表,则已包含在内

相关问题 更多 >