【问题标题】:Python - make a dictionary from a csv file with multiple categoriesPython - 从具有多个类别的 csv 文件制作字典
【发布时间】:2013-07-25 14:46:31
【问题描述】:

我正在尝试从 python 中的 csv 文件制作字典,但我有多个类别。我希望键是 ID 号,值是项目的名称。这是文本文件:

"ID#","name","quantity","price"
"1","hello kitty","4","9999"
"2","rilakkuma","3","999"
"3","keroppi","5","1000"
"4","korilakkuma","6","699"

这就是我目前所拥有的:

txt = open("hk.txt","rU")

file_data = txt.read()
lst = []           #first make a list, and then convert it into a dictionary.
for key in file_data:
        k = key.split(",")
        lst.append((k[0],k[1]))

dic = dict(lst)
print(dic)

这只是打印一个空列表。我希望键是 ID#,然后值将是产品的名称。我将制作另一个字典,其中名称作为键,ID# 作为值,但我认为这将是同一件事,但反过来。

【问题讨论】:

    标签: python csv dictionary python-3.x


    【解决方案1】:

    使用csv module 处理您的数据;它将删除引用并处理拆分:

    results = {}
    
    with open('hk.txt', 'r', newline='') as txt:
        reader = csv.reader(txt)
        next(reader, None)  # skip the header line
        for row in reader:
            results[row[0]] = row[1]
    

    对于您的示例输入,这会产生:

    {'4': 'korilakkuma', '1': 'hello kitty', '3': 'keroppi', '2': 'rilakkuma'}
    

    【讨论】:

      【解决方案2】:

      你可以使用csv DictReader:

      import csv
      
      result={}
      with open('/tmp/test.csv', 'r', newline='') as f:
          for d in csv.DictReader(f):
              result[d['ID#']]=d['name']
      
      print(result)
      # {'1': 'hello kitty', '3': 'keroppi', '2': 'rilakkuma', '4': 'korilakkuma'}
      

      【讨论】:

      • 注意OP使用的是Python 3,所以推荐使用newline=''参数。
      • 我会解决的。谢谢!
      【解决方案3】:

      您可以直接使用字典:

      dictionary = {}
      file_data.readline()   # skip the first line         
      for key in file_data:
          key = key.replace('"', '').strip()
          k = key.split(",")
          dictionary[k[0]] = k[1]
      

      【讨论】:

      • 我试过这种方式,这很好。 :) 但是,结果是这样打印的:{'"3"': '"keroppi"', '"4"': '"korilakkuma"', '"1"': '"hello kitty"', '"2"': '"rilakkuma"', '"ID#"': '"name"'}
      • 对不起,我是这个网站的新手,所以我不太擅长格式化。
      • 我的意思是我的答案的编辑。我添加了key = key.replace('"', '').strip() 行。这应该删除您看到的双引号。
      【解决方案4】:

      试试这个或使用任何库来读取文件。

      txt = open("hk.txt","rU")
      
      file_data = txt.read()
      file_lines = file_data.split("\n")
      lst = []           #first make a list, and then convert it into a dictionary.
      for linenumber in range(1,len(file_lines)):
              k = file_lines[linenumber].split(",")
              lst.append((k[0][1:len(k[0])-1],k[1][1:len(k[1])-1]))
      
      dic = dict(lst)
      print(dic)
      

      但你也可以直接使用字典。

      【讨论】:

        猜你喜欢
        • 2021-06-15
        • 2014-03-20
        • 1970-01-01
        • 1970-01-01
        • 2015-07-25
        • 1970-01-01
        • 1970-01-01
        • 2020-06-05
        • 1970-01-01
        相关资源
        最近更新 更多