[英]How to convert CSV to a more structured dictionary in 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 StoreA
是否有一些Python简单的方法,让我基于某些领域我期望能够产生结构化字典“崩溃?” 例如,通过依次指定“类型”,“应用程序”,“名称” ...,它将创建仅具有三个键“ Vegetable”,“ Fruit”,“ Dairy”的字典。
蔬菜将只有“ StoreA”和“ StoreB”,水果将只有“ Store B”和“ C”(即使在商店B中有梅子也没有重复的商店B)
而钻探到dict最深的层次就是结果。 做到这一点的最佳方法是什么? 赞赏语法。
由于这似乎并不像一个有关分析CSV的问题,我会假设你可以得到你的数据导入使用以下格式csv.DictReader
或其他一些方法:
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'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.