【问题标题】:How to add values to keys in a dictionary for keys found in a file? Python如何为文件中找到的键向字典中的键添加值? Python
【发布时间】:2016-07-26 11:37:54
【问题描述】:

所以我有一个 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”没有像我预期的那样工作(向键添加值)。有什么建议么?谢谢!

【问题讨论】:

  • 你有没有尝试过什么?
  • 一堆东西,但没有一个有用,我决定不分享。
  • 如何在 python 中添加元素list,你知道吗?
  • 是的,有附加。我已经尝试通过目录和价格进行迭代。追加,但它只是添加每个键的所有价格。问题是我不知道如何在文件中搜索密钥,然后返回与该密钥对应的价格。
  • 我认为最好显示 full_catalog 的样子,您的索引方式令人困惑。

标签: python list file python-3.x dictionary


【解决方案1】:

我建议在浏览文件时创建字典,而不是将它们添加到列表中然后再通过它来构建字典。

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 如果您仍需要完整列表,则已包含在其中

【讨论】:

    猜你喜欢
    • 2020-06-10
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 2017-01-04
    相关资源
    最近更新 更多