简体   繁体   中英

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. 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. Also, you can't use same key twice, hence one of the situations where 2 is used as key will be overwritten.

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,

The csv file,

$ 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']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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