簡體   English   中英

在Python中將字典的值分組在一起

[英]Grouping values of a dictionary together in Python

我有以下字典:

comb_dict = 
['1d812hjbsa' : ['Apple', 'iPad'], '190usdnb1' : ['Amazon', 'Kindle'], 'sjdb1892': ['Apple', 'iPad'], '23ub8wh12' : ['Apple', 'iPhone'], '12ndsi01' : ['Amazon', 'Kindle'] ]

關鍵是交易ID,值是公司和產品名稱。 我正在嘗試將公司和產品分組,然后計算在內。 對於此示例,我期望輸出如下:

fin_dict=
[ ['Apple', 'iPad'] : 2, '['Amazon', 'Kindle'] : 2, ['Apple', 'iPhone', : 1 ]

我試圖將數據讀入新字典中,鍵值從輸入中反轉。 但是,它沒有按我預期的那樣工作並拋出以下錯誤:

for key, value in comb_dict.items():
    if fin_dict.has_key(value):
        fin_dict[value] +=1
    else:
        fin_dict.update({value : 1})  

Output

   if fin_dict.has_key(value):
TypeError: unhashable type: 'list'

有人可以指出如何解決此問題嗎?

謝謝,TM

您的字典鍵不能是列表,因為列表是可變的。 您需要一個元組或其他不可變的對象。

我建議您改為使用計數器。

>>> from collections import Counter
>>> dic = {'1d812hjbsa' : ['Apple', 'iPad'], '190usdnb1' : ['Amazon', 'Kindle'], 'sjdb1892': ['Apple', 'iPad'], '23ub8wh12' : ['Apple', 'iPhone'], '12ndsi01' : ['Amazon', 'Kindle']}
>>> counter = Counter(tuple(v) for v in dic.values())
>>> dict(counter)
{('Amazon', 'Kindle'): 2, ('Apple', 'iPad'): 2, ('Apple', 'iPhone'): 1}

此外,請勿使用已棄用的has_key() 而是使用in關鍵字。 例如, if value in fin_dict:

該錯誤消息告訴您出了什么問題:您不能將列表用作字典鍵,因為列表不可散列。

幸運的是,您可以將其轉換為可哈希的元組。 請注意,在collections.Counter中有一個不錯的類已經為您進行計數。

import collections
fin = collections.Counter(tuple(i) for i in comb.values())

發生錯誤,因為列表不可散列。 例如,您可以將列表轉換為逗號分隔的字符串:

fin_dict = {}

for t in comb_dict:
    hash = ",".join(comb_dict[t])
    if not fin_dict.has_key(hash):
        fin_dict[hash] = 1
    else:
       fin_dict[hash] += 1

我看到兩個問題:

  1. 您正在使用方括號[]而不是大括號{}來定義字典。 方括號括住列表而不是字典。

  2. 您正在嘗試將列表用作第二個dict(fin_dict)中的鍵,這是不允許的。 嘗試將您的comb_dict值的第二個元素引用為fin_dict中的唯一鍵:

     comb_dict = {'1d812hjbsa' : ['Apple', 'iPad'], '190usdnb1' : ['Amazon', 'Kindle'], 'sjdb1892':['Apple', 'iPad'], '23ub8wh12' : ['Apple', 'iPhone'], '12ndsi01' : ['Amazon', 'Kindle'] } fin_dict={'iPad': 0, 'Kindle' : 0, 'iPhone' : 0} for key, value in comb_dict.items(): if value[1] in fin_dict: fin_dict[value[1]] +=1 else: print("unsupported device") # or exception handling 

暫無
暫無

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

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