因爲這似乎並不像一個有關分析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'])
你有沒有想過使用數據庫,如[SQLite](http://docs.python.org/2/library/sqlite3.html)? –
使用defaultdicts創建一個遞歸結構,我認爲有幾行會做到這一點 –