【问题标题】:Build a function that take CSV as argument and returns dictionary构建一个以 CSV 作为参数并返回字典的函数
【发布时间】:2021-07-30 10:50:51
【问题描述】:

我正在尝试构建一个函数,它获取一个 csv 文件作为参数并返回一个字典,而不使用 pandas 或任何其他类似的工具。 我想要做的是获取一个字典,其中键是国家名称,值是他们在奥运会上获得的奖牌数量(如果他们没有获得任何奖牌,则应该返回 0)。 这就是我试图做的(不知道如何把它放在一个函数中)。

def summer_olympic_stats(file):
summer_olympic_medals = {}
with open("summer_olympics_countries.csv", "r+") as my_csv:
        for line in my_csv:
            line = line.rstrip("\n")
            medals = line.startswith("Gold") or line.startswith("Silver") or line.startswith("Bronze") or line.startswith("Total")
            country = row[1]
            country,medals = line.split("\t")
            summer_olympic_medals[country] = int(medals)
print(summer_olympic_stats(open("summer_olympics_countries.csv")))

我得到的错误代码是:

PermissionError: [Errno 13] Permission denied: 'summer_olympics_countries.csv'

我想要得到的结果示例:

{'ALG': {'Gold': 5, 'Silver': 4, 'Bronze': 8, 'Total': 17}}

为了澄清起见,csv 文件如下所示:

我知道我的 func 甚至没有接近解决方案,但我真的不知道如何处理它,这是我使用 python 的第三周,所以这是我在这个世界上的第一步。 感谢所有帮助,谢谢!

【问题讨论】:

  • 您的意思是:open("summer_olympics_countries.csv", "r")
  • 解决了这个错误,谢谢!我再试一次
  • 以“r+”模式打开应该也可以,但是由于该模式可能涉及文件写入,因此您必须关闭要打开的文件,否则会出现权限被拒绝错误即运行脚本时不能在excel中打开数据
  • 您可以将示例数据添加为文本或最终添加为文件链接 - 然后我们可以在数据上测试代码。

标签: python python-3.x function csv dictionary


【解决方案1】:

阅读How CSV data is represented(直到 Python CSV 模块之前的部分就足够了)寻求帮助:

def summer_olympic_stats(file):
    summer_olympic_medals = {}
    with open(file, "r") as my_csv:
        data = my_csv.read().split("\n") # data is now a list, where each element is a line from the csv file

        # We want to find the index of country, gold medal, silver medal and bronze medal
        # So we can use the same indices to get their number
        country_index = 0
        gold_index = 0
        silver_index = 0
        bronze_index = 0

        headings = data[0].split(",")
        
        for heading in headings:
            if "Country" == heading:
                country_index = headings.index(heading)
            elif "Gold" == heading:
                gold_index = headings.index(heading)
            elif "Silver" == heading:
                silver_index = headings.index(heading)
            elif "Bronze" == heading:
                bronze_index = headings.index(heading)

        for line in data[1:]: # The first line is only headings and we dont need to iterate over that
            line = line.split(",") # Divides the line into list containing its components
            
            # Update dictionary in required format, with the help of country_index, gold_index, silver_index, bronze_index
            summer_olympic_medals.update({
                line[country_index] : {
                    "Gold": line[gold_index],
                    "Silver": line[silver_index],
                    "Bronze": line[bronze_index]
                }
            
            })
        
        return summer_olympic_medals

【讨论】:

  • 谢谢!我现在理解得更好了......但是您的解决方案的输出给出了这个:{'1': {'Gold': '1', 'Silver': '1', 'Bronze': '1', 'total': '1'},,而输出应该是:'{'ALG': {'Gold': 5, 'Silver': 4, 'Bronze': 8, 'Total': 17}}'
  • @ranbar 修复:country_index = heading.index(heading)country_index = headings.index(heading)。标题.index 到标题s.index()。 for heading in headings 循环中的其他 3 个相同。在原始答案中也已修复,不知道这是怎么发生的。谢谢指出
【解决方案2】:

您可以使用 pandas 导入 csv

import pandas

data = pandas.read_csv("path")

#create a dataframe

df = pd.DataFrame({'col1': data["col1"],
                   'col2': ["col2"]},
                  index=['row1', 'row2'])

#create dictionary from dataframe
req_dict = "df.to_dict()"

【讨论】:

  • 谢谢,但我试图在不使用 pandas 的情况下解决它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-27
  • 2017-03-17
  • 1970-01-01
相关资源
最近更新 更多