[英]Converting tuple of dict into tuple of tuple of dict in python
我有dict元組格式的查詢結果集數據。 我想根據特定條件將數據分組為dict元組。
實際輸出:
({'col1': 2014},
{'col1': 2013},
{'col1': 2014},
{'col1': 2013},
{'col1': 2015},
{'col2': '24'})
預期產量:此處我們按年份分組
(({'col1': 2014}, {'col1': 2014}),
({'col1': 2013}, {'col1': 2013}),
({'col1': 2015}, {'col2': '24'}))
請指導我們獲取數據,而我們正在處理查詢,而不是一個接一個地處理記錄並轉換為特定的格式。
您可以根據年份對字典進行排序,然后將groupby
與year作為key
:
>>> from itertools import groupby
>>> t = ({'col1':2014},{'col1':2013},{'col1':2014},{'col1':2013},{'col1':2015})
>>> key = lambda x: x['col1']
>>> tuple(tuple(g) for k, g in groupby(sorted(t, key=key), key))
(({'col1': 2013}, {'col1': 2013}), ({'col1': 2014}, {'col1': 2014}), ({'col1': 2015},))
groupby
將使用相同的鍵對連續元素進行分組並返回(key, iterable)
元組。 然后,在生成器表達式中將每個可迭代對象轉換為元組,該表達式作為tuple
的參數給出。
更新 :上面的一類代碼對數據進行排序具有O(n log n)的時間復雜度。 使用更多行,可以使用defaultdict
在O(n)時間完成任務:
>>> from collections import defaultdict
>>> t = ({'col1':2014},{'col1':2013},{'col1':2014},{'col1':2013},{'col1':2015})
>>> dd = defaultdict(list)
>>> for d in t:
... dd[d['col1']].append(d)
...
>>> tuple(tuple(v) for k, v in dd.items())
(({'col1': 2013}, {'col1': 2013}), ({'col1': 2014}, {'col1': 2014}),({'col1': 2015},))
注意,這將以任意順序返回組,因為dict
是無序集合。 如果您需要按“完整”組(每年僅一組)處理數據,而又無法使數據庫按排序順序返回數據,那么這是您的最佳選擇。
如果可以按排序的順序從數據庫中獲取數據,則仍然可以使用groupby
而不需要先提取所有內容:
from itertools import groupby
cursor = iter([2013, 2013, 2014, 2014, 2014, 2015, 2015])
def get_batch():
batch = []
try:
for _ in range(3):
batch.append({'col1': next(cursor)})
except StopIteration:
pass
print('Got batch')
return batch
def fetch():
while True:
batch = get_batch()
if not batch:
break
yield from batch
for k, g in groupby(fetch(), lambda x: x['col1']):
print('Group: {}'.format(tuple(g)))
輸出:
Got batch
Group: ({'col1': 2013}, {'col1': 2013})
Got batch
Group: ({'col1': 2014}, {'col1': 2014}, {'col1': 2014})
Got batch
Got batch
Group: ({'col1': 2015}, {'col1': 2015})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.