2014-02-12 25 views
-1

我正打算用字典替換一個小的sql數據庫。我面臨的唯一問題是查詢。它變得如此複雜。這裏是例子:如何從python字典查詢?

foo={'id_1': {'location': 'location_1', 'material': 'A'}, 
    'id_2': {'location': 'location_1', 'material': 'A'}, 
    'id_3': {'location': 'location_1', 'material': 'B'}, 
    'id_4': {'location': 'location_2', 'material': 'B'}, 
    'id_5': {'location': 'location_2', 'material': 'A'}, 
    'id_6': {'location': 'location_1', 'material': 'C'}, 
    'id_7': {'location': 'location_1', 'material': 'A'}, 
    'id_8': {'location': 'location_2', 'material': 'B'}} 

所以,我想給一些查詢基於位置和結果應該是這樣的:

{'location_1' : {'A': 3, 'B': 1, 'C': 1}, 'location_2': {'A':1,'B':2}} 

有沒有辦法做到在Python字典查詢?或者至少乾淨利落的做法呢?

感謝

+0

而什麼叫 「查詢」 是什麼意思? –

+1

不像在小型SQL數據庫中那樣容易。你爲什麼要替換它? – geoffspear

+0

'dict'不是關係數據庫。你可以通過一個鍵進行「查詢」,或者循環查找所需的全部內容。 – roippi

回答

1

你需要使用一個defaultdict()Counter()對象,以達到你想要的東西:

results = defaultdict(Counter) 
for entry in foo.values(): 
    results[entry['location']][entry['material']] += 1 

主要生產:

defaultdict(<class 'collections.Counter'>, { 
    'location_2': Counter({'B': 2, 'A': 1}), 
    'location_1': Counter({'A': 3, 'C': 1, 'B': 1}) 
}) 

但使用一個實際的數據庫(如作爲捆綁的sqlite3)會更有效率。

1

如何:

d = {} 
for k,v in foo.iteritems(): 
    loc = v['location'] 
    mat = v['material'] 
    d.setdefault(loc, {}) 
    d[loc].setdefault(mat, 0) 
    d[loc][mat] = d[loc].get(mat, 0) + 1 
print d 

輸出:

{'location_2': {'A': 1, 'B': 2}, 'location_1': {'A': 3, 'C': 1, 'B': 1}}