使用csv.DictReader创建嵌套字典 [英] Creating nested dict using csv.DictReader

查看:68
本文介绍了使用csv.DictReader创建嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python csv模块,并且我有一个包含3的CSV列,项目,零件,类别.

I am using the python csv module and I have a CSV with 3 columns, Item, Part, Category.

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

I'd like to create a dict that combines all the categories and then sorts their values with the 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的内置函数来做到这一点:

I'd leverage the use of Python's built-ins to do it:

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 .

FWIW, you could also do it this way, which takes a few more lines of code, but would make what's going on in the inner-loop a little more readable. The result would be identical. Note it uses csv.reader not 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

这篇关于使用csv.DictReader创建嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆