gpt4 book ai didi

python - 使用 csv.DictReader 创建嵌套字典

转载 作者:行者123 更新时间:2023-11-30 23:08:42 28 4
gpt4 key购买 nike

我正在使用python csv module我有一个包含 3 列的 CSV:项目、零件、类别。

我想创建一个字典来组合所有类别,然后使用 Item:Part 对它们的值进行排序。

例如:

512 SSD SATA,42-000153,Hardware
5M DisplayPort 1.2 Cable,42-000135,Cable
90W AC Adapter,42-000146,Adapter
4 port USB hub,42-000126,Adapter

我得到的结果是:

mydict = {
Hardware:{512 SSD SATA:42-000153},
Cable:{5M DisplayPort 1.2 Cable,42-000135},
Adapter:{90W AC Adapter:42-000146},
Adapter:{4 port USB hub:42-000126}
}

这几乎让我到达那里:

def build_dict(source_file):
projects = defaultdict(dict)
headers = ['Product', 'Part Number', 'Category']
with open(source_file, 'rb') as fp:
reader = csv.DictReader(fp, fieldnames=headers, dialect='excel',
skipinitialspace=True)
for rowdict in reader:
if None in rowdict:
del rowdict[None]
category = rowdict.pop("Category")
projects[category] = rowdict
return dict(projects)

source_file = 'test.csv'

我正在寻找的结果:

mydict = {
Hardware:{512 SSD SATA:42-000153},
Cable:{5M DisplayPort 1.2 Cable,42-000135},
Adapter:{90W AC Adapter:42-000146,4 port USB hub:42-000126}
}

请帮忙!

最佳答案

我会利用 Python 的内置函数来做到这一点:

import csv
from collections import defaultdict

mydict = defaultdict(dict)
with open('inventory.csv', 'rb') as inf:
for row in csv.DictReader(inf, fieldnames=['Product', 'Part Number',
'Category']):
mydict[row['Category']][row['Product']] = row['Part Number']

import json # for pretty-printing result
print(json.dumps(mydict, indent=4))

输出:

{
"Hardware": {
"512 SSD SATA": "42-000153"
},
"Adapter": {
"4 port USB hub": "42-000126",
"90W AC Adapter": "42-000146"
},
"Cable": {
"5M DisplayPort 1.2 Cable": "42-000135"
}
}

FWIW,您也可以这样做,这需要多几行代码,但会使内循环中发生的事情更具可读性。结果是相同的。请注意,它使用 csv.reader 而不是 csv.DictReader

import csv
from collections import defaultdict
from collections import namedtuple

Record = namedtuple('Record', ['product', 'part_number', 'category'])

mydict = defaultdict(dict)
with open('inventory.csv', 'rb') as inf:
for rec in map(Record._make, csv.reader(inf)):
mydict[rec.category][rec.product] = rec.part_number # more readable

关于python - 使用 csv.DictReader 创建嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31600296/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com