1

Hello I have a CSV file of the format below:

ticket asset
1111   3456
1111   6789
1122   2345
1122   7890

I want to convert it to a Dict like:

{'1111': ['3456', '6789'], '1122':['2345', '7890']}

Basically want to have the ticket as 'key' and all the assets under that ticket as 'values'.

the csv.DictReader() helped a little but I am unable to extract unique ticket number for keys and match all the asset under it for values.

Any help would be great :)

Thanks for getting the CSV > Dict so quick!

If I want to convert a Tuple to Dict, how will that work?

e.g: Tuple: ((1111, 3456), (1111, 6789), (1122, 2345), (1122, 7890))

and I want that to be converted to:

{'1111': ['3456', '6789'], '1122':['2345', '7890']}

Karthik
  • 29
  • 1
  • 4

2 Answers2

7

Using collections.defaultdict:

from collections import defaultdict
import csv

d = defaultdict(list)
with open(filename, 'r', newline='') as f:
    reader = csv.reader(f, delimiter='\t')
    next(reader) # toss headers
    for ticket, asset in reader:
        d[ticket].append(asset)

With regular dictionary:

import csv

d = {}
with open(filename, 'r', newline='') as f:
    reader = csv.reader(f, delimiter='\t')
    next(reader) # toss headers
    for ticket, asset in reader:
        d.setdefault(ticket, []).append(asset)
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
0

Import your csv into a pandas dataframe. Use applymap to convert the dataframe into string data type. Group by ticket and convert all collected asset as a list. Then convert the dataframe into a dictionary(dict)

import pandas as pd
df=pd.read_csv('file.csv', header=0)
df=df.applymap(str).groupby('ticket')['asset'].apply(list).to_dict()
print(df)

Result:

{'1111': ['3456', '6789'], '1122': ['2345', '7890']}
jose_bacoy
  • 12,227
  • 1
  • 20
  • 38