簡體   English   中英

字典python組列表

[英]Group list of dictionaries python

如何在列表中對字典的類似鍵進行分組

如果我有

data = [{'quantity': 2, 'type': 'Vip'}, {'quantity': 23, 'type': 'Vip'}, {'quantity': 2, 'type': 'Regular'}, {'quantity': 2, 'type': 'Regular'}, {'quantity': 2, 'type': 'Regular'}, {'quantity': 2, 'type': 'Regular'}]

我希望它像這樣輸出

res = {'Regular': [{'quantity': 2, 'type': 'Regular'},{'quantity': 2, 'type': 'Regular'},{'quantity': 2, 'type': 'Regular'}], 'Vip': [{'quantity': 23, 'type': 'Vip'},{'quantity': 23, 'type': 'Vip'}]}

這是我試過的代碼,但它給了我兩倍的關鍵可能是因為循環

 res = defaultdict(list)
 for i in data:
    if len(res) >= 1:
       for q in res:
          if q == i['type']:
            res[q].append(i)
            break
          else:
            res[i['type']].append(i)
            break
  res[i['type']].append(i)

我想你不完全理解defaultdict的想法。 如果查找時不存在defaultdict將生成新對象。

所以你可以簡單地使用:

from collections import defaultdict

res = defaultdict(list)

for i in data:
    res[i['type']].append(i)

產量:

>>> pprint(res)
defaultdict(<class 'list'>,
            {'Regular': [{'quantity': 2, 'type': 'Regular'},
                         {'quantity': 2, 'type': 'Regular'},
                         {'quantity': 2, 'type': 'Regular'},
                         {'quantity': 2, 'type': 'Regular'}],
             'Vip': [{'quantity': 2, 'type': 'Vip'},
                     {'quantity': 23, 'type': 'Vip'}]})

pprint漂亮 ,但不會改變內容)。

請注意,這里我們將對字典的引用復制到新列表中,因此我們不會創建新的字典。 此外,結果是defaultdict 我們可以用dict(res)將它轉換成一個vanilla字典。

您的數據模型非常冗余。 您可以使用type為鍵的dict和數量列表作為值。

data = [{'quantity': 2, 'type': 'Vip'}, {'quantity': 23, 'type': 'Vip'}, {'quantity': 2, 'type': 'Regular'}, {'quantity': 2, 'type': 'Regular'}, {'quantity': 2, 'type': 'Regular'}, {'quantity': 2, 'type': 'Regular'}]

res = {}

for d in data:
    res.setdefault(d['type'], []).append(d['quantity'])

print(res)
# {'Vip': [2, 23], 'Regular': [2, 2, 2, 2]}

輸出要短得多,但你沒有丟失任何信息。

如果您只對總數量感興趣,可以使用Counter

from collections import Counter
count = Counter()
for d in data:
    count[d['type']] += d['quantity']

print(count)
# Counter({'Vip': 25, 'Regular': 8})
~                                         

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM