簡體   English   中英

從計算元組項出現次數的元組創建嵌套字典

[英]Creating a nested dictionary from tuples that counts the number of occurrences of a tuple item

我必須對元組列表進行排序並創建一個字典,其中元組中的第一項作為鍵,嵌套字典將鍵作為第二項,出現次數作為值。 我不確定如何解決這個問題,任何幫助都會很棒。

[('academic', 'hacked'), ('academic', 'lost device'), ('academic', 'lost device'), ('academic', 'lost device'), ('energy', 'inside job'), ('financial', 'hacked')]

所需的 output:

{'academic': {'lost device': 3, 'hacked': 1}, 'energy': {'inside job': 1}, 'financial': {'hacked': 1}}

這不是pythonic的方式,但至少它正在工作

mylist = [('academic', 'hacked'), ('academic', 'lost device'), ('academic', 'lost device'), ('academic', 'lost device'), ('energy', 'inside job'), ('financial', 'hacked')]        

dict = {}
for el in mylist:
  if not el[0] in dict.keys():
    dict[el[0]] = {}
  if not el[1] in dict[el[0]].keys():
    dict[el[0]][el[1]] = 1
  else:
    dict[el[0]][el[1]] += 1        
print (dict)

結果我得到:

{'academic': {'hacked': 1, 'lost device': 3}, 'energy': {'inside job': 1}, 'financial': {'hacked': 1}}

使用setdefault - 這很好:

x={}
for a,b in mylist:
   c=x.setdefault(a,{})
   c[b]=c.setdefault(b,0)+1
print(x)

您可以使用Collections.Counter在一行中執行此操作,如下所示。 這里, vals是元組列表。

from collections import Counter
dict((k[0],{k[1]:v})for k, v in Counter(vals).items())

解決方案

from collections import Counter
vals = [('academic', 'hacked'), ('academic', 'lost device'), ('academic', 'lost device'), 
        ('academic', 'lost device'), ('energy', 'inside job'), ('financial', 'hacked')]

output = dict((k[0],{k[1]:v})for k, v in Counter(vals).items())
print(output)

結果

{'academic': {'hacked': 1, 'lost device': 3}, 'energy': {'inside job': 1}, 'financial': {'hacked': 1}}

暫無
暫無

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

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