我想用字典替换一个小的sql数据库。我面临的唯一问题是查询。它变得如此复杂。这是一个例子:
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)
您需要使用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 :(得分: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}}