简体   繁体   English

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

[英]how to create dictionary with comma separated file

Plz suggest how to create dictionary from the following file contetns请建议如何从以下文件内容创建字典

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

my required output is我需要的输出是

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

I am new to python and I tried below code but It is not working.我是 python 的新手,我尝试了下面的代码,但它不起作用。 Please suggest请建议

   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)

The problem is because the DictReader thinks first row is field mapping, so number 2 will be used as key for next rows.问题是因为DictReader认为第一行是字段映射,所以数字 2 将用作下一行的键。 Also, you can't use same key twice, hence one of the situations where 2 is used as key will be overwritten.此外,您不能两次使用相同的密钥,因此将覆盖使用 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)

Output:输出:

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

You could use defaultdict from collections to handle the unique keys,您可以使用collections defaultdict来处理唯一键,

The csv file, .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))

And the output,而输出,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM