如何用逗号分隔文件创建字典

时间:2019-04-03 11:48:18

标签: python

Plz建议如何根据以下文件内容创建字典

2,20190327.1.csv.gz
3,20190327.23.csv.gz
4,20190327.21302.csv.gz
2,20190327.24562.csv.gz

我所需的输出是

{2:20190327.1.csv.gz:982, 3:20190327.23.csv.gz, 4:20190327.21302.csv.gz, 2:20190327.24562.csv.gz}

我是python的新手,我尝试了以下代码,但无法正常工作。请建议

   from __future__ import print_function
   import csv
   file = '/tmp/.fileA'
      with open(file) as fh:
        rd = csv.DictReader(fh, delimiter=',')
        for row in rd:
            print(row)

2 个答案:

答案 0 :(得分:0)

问题是因为DictReader认为第一行是字段映射,所以数字2将用作下一行的键。另外,您不能两次使用相同的密钥,因此使用2作为密钥的情况之一将被覆盖。

import csv
file = 'data.csv'

my_dict = {}
with open(file) as fh:
    rd = csv.reader(fh, delimiter=',')
    for row in rd:
        my_dict[row[0]] = row[1]

print(my_dict)

输出:

 $ python3 reader.py 
{'2': '20190327.24562.csv.gz', '3': '20190327.23.csv.gz', '4': '20190327.21302.csv.gz'}

答案 1 :(得分:0)

您可以使用defaultdict中的collections来处理唯一键,

csv文件

$ cat some.csv
2,20190327.1.csv.gz
3,20190327.23.csv.gz
4,20190327.21302.csv.gz
2,20190327.24562.csv.gz


$ cat mkdict.py
import csv
from collections import defaultdict

import pprint

d = defaultdict(list)
with open('some.csv') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    for row in reader:
        if row: # taking care for empty lines :)
            key, value = row
            d[key].append(value)

pprint.pprint(dict(d))

输出,

$ python mkdict.py
{'2': ['20190327.1.csv.gz', '20190327.24562.csv.gz'],
 '3': ['20190327.23.csv.gz'],
 '4': ['20190327.21302.csv.gz']}