如何在python中将CSV转换为更结构化的字典?
假设我有以下CSV:如何在python中将CSV转换为更结构化的字典?,python,Python,假设我有以下CSV: Type Name Application Vegetable Lettuce StoreA Fruit Apple StoreB Vegetable Orange StoreB Fruit Pear StoreC Dairy Milk StoreA Fruit Plum StoreB Fruit Plum St
Type Name Application
Vegetable Lettuce StoreA
Fruit Apple StoreB
Vegetable Orange StoreB
Fruit Pear StoreC
Dairy Milk StoreA
Fruit Plum StoreB
Fruit Plum StoreA
在python中是否有一些简单的方法可以让我根据我希望“折叠”的某些字段生成结构化dict?例如,按顺序指定“类型”,然后指定“应用程序”,然后指定“名称”。。。它将创建一个只有三个键的dict“蔬菜”、“水果”、“奶制品”
蔬菜只有“StoreA”和“StoreB”
水果将有“存储B”和“存储C”(即使李子在存储B中,也没有重复的存储B)
而钻研到最深层次的格言将是果实。实现这一目标的最佳方式是什么?语法很受欢迎。由于解析CSV似乎没有问题,我假设您可以使用或其他方法将数据转换为以下格式:
rows = [{'Type': 'Vegetable', 'Name': 'Lettuce', 'Application': 'StoreA'},
{'Type': 'Fruit', 'Name': 'Apple', 'Application': 'StoreB'},
{'Type': 'Vegetable', 'Name': 'Orange', 'Application': 'StoreB'},
{'Type': 'Fruit', 'Name': 'Pear', 'Application': 'StoreC'},
{'Type': 'Dairy', 'Name': 'Milk', 'Application': 'StoreA'},
{'Type': 'Fruit', 'Name': 'Plum', 'Application': 'StoreB'},
{'Type': 'Fruit', 'Name': 'Plum', 'Application': 'StoreA'}]
一旦您找到了,这里有一个选项用于创建您要查找的嵌套字典:
result = {}
for row in rows:
stores = result.setdefault(row['Type'], {})
names = stores.setdefault(row['Application'], [])
names.append(row['Name'])
>>> pprint.pprint(result)
{'Dairy': {'StoreA': ['Milk']},
'Fruit': {'StoreA': ['Plum'],
'StoreB': ['Apple', 'Plum'],
'StoreC': ['Pear']},
'Vegetable': {'StoreA': ['Lettuce'],
'StoreB': ['Orange']}}
当然,您可以将for
循环的内容放在一行上:
for row in rows:
result.setdefault(row['Type'], {}).setdefault(row['Application'], []).append(row['Name'])
您是否考虑过使用数据库,例如?使用defaultdicts来创建递归结构,我认为很少有行可以做到这一点