[英]How to count unique key elements in a tuple in a defaultdict (python)?
我有以下字典,鍵是元組:
defaultdict(<class 'float'>, {('abc', 'xyz'): 1.0, ('abc', 'def'):
3.0, ('abc', 'pqr'): 1.0, ('pqr', 'xyz'): 1.0, ('pqr', 'def'): 1.0})
我如何計算第一個關鍵元素和第二個關鍵元素,以便我可以得到:
defaultdict(<class 'float'>, {'abc': 3.0, 'pqr': 3.0})
和
defaultdict(<class 'float'>, {'xyz': 2.0, 'def': 2.0, 'pqr': 1.0})
我忽略了原始字典中的值,只計算了唯一鍵(分別為第一個和第二個)。
我想做類似以下的事情,但我收到錯誤“'tuple'對象沒有屬性'items'”:
first_key_list =[j[0][0] for i in dictionary for j in i.items()]
new_dict = collections.defaultdict(float)
for i in first_key_list:
new_dict[i] += 1
你的方法是正確的。 但是如果你想計算東西,我建議使用Counter
對象。
from collections import Counter
c1 = Counter(k[0] for k in d.keys())
c2 = Counter(k[1] for k in d.keys())
說實話, d.keys()
在這里是多余的,因為默認情況下迭代在鍵上。
c1
Counter({'abc': 3, 'pqr': 2})
c2
Counter({'def': 2, 'pqr': 1, 'xyz': 2})
因為外部循環產生字典鍵(元組),並且items
不適用於tuples
for i in dictionary for j in i.items()
中的for i in dictionary for j in i.items()
。
無論如何,你似乎忽略了詞典的價值觀。 只需在密鑰的第一部分使用collections.Counter
:
d = {('abc', 'xyz'): 1.0, ('abc', 'def'):
3.0, ('abc', 'pqr'): 1.0, ('pqr', 'xyz'): 1.0, ('pqr', 'def'): 1.0}
import collections
d1 = collections.Counter(k[0] for k in d)
print(d1)
結果:
Counter({'abc': 3, 'pqr': 2})
如果你想要浮點數,我建議你在計算以避免浮點不准確后轉換為浮點數:
{k:float(v) for k,v in d1.items()}
或者在一行中:
d1 = {k:float(v) for k,v in collections.Counter(k[0] for k in d).items()}
將密鑰保持為元組:
d1 = {(k,):float(v) for k,v in collections.Counter(k[0] for k in d).items()}
對於第二部分,只需使用k[1]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.