以一栏为键,一栏为值将CSV转换为字典 [英] Converting CSV to Dictionary with one column as keys and one column as its values
问题描述
您好,我有以下格式的CSV文件:
Hello I have a CSV file of the format below:
ticket asset
1111 3456
1111 6789
1122 2345
1122 7890
我想将其转换为类似Dict的Dict.
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'.
csv.DictReader()有所帮助,但是我无法为密钥提取唯一的凭单号,也无法匹配其下的所有资产作为值.
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.
任何帮助都会很棒:)
感谢您快速获得CSV>词典!
Thanks for getting the CSV > Dict so quick!
如果我想将元组转换为Dict,那将如何工作?
If I want to convert a Tuple to Dict, how will that work?
例如:元组:((1111,3456),(1111,6789),(1122,2345),(1122,7890))
e.g: Tuple: ((1111, 3456), (1111, 6789), (1122, 2345), (1122, 7890))
,我希望将其转换为:
{'1111':['3456','6789'],'1122':['2345','7890']}
{'1111': ['3456', '6789'], '1122':['2345', '7890']}
推荐答案
使用 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)
使用常规词典:
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)
这篇关于以一栏为键,一栏为值将CSV转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!