1

Python 2.6 を使用する場合:

各キーに値のリストが含まれる辞書があります。

ディクショナリ内のすべての値を調べて、すべてのキーでそれぞれが何回出現するかを集計したいと考えています。

私は itervalues() またはを見てきました

for value in dictionary.values():

まず、.count() 関数ですが、ヒストグラムを返す必要があります。

例えば:

print dictionary

戻るだろう

{'test' : ['spam', 'eggs', 'cheese', 'spam'], 'test2' : ['spam', 'cheese', 'goats']}

そして、私は私に何か言いたいです:

{'spam' : 3, 'eggs' : 1, 'cheese': 2, 'goats' : 1}
4

2 に答える 2

6
from collections import Counter

d = {'test' : ['spam', 'eggs', 'cheese', 'spam'], 'test2' : ['spam', 'cheese', 'goats']}
c = Counter(sum(d.values(), []))
# or c = Counter(x for a in d.values() for x in a)
print c.most_common()

## [('spam', 3), ('cheese', 2), ('eggs', 1), ('goats', 1)]

Python 2.6 の場合、このレシピを使用します。

于 2012-04-24T18:31:44.903 に答える
2

値のリストを反復処理し、1 つずつインクリメントして新しい辞書に追加します。

# start with an empty output dictionary
out = {}

# iterate through the keys in the dictionary
for key in p:
   # iterate through the values in the sublist
   for val in p[key]:
      # check to see if we've seen this one before
      if not out.has_key(val):
         # if not, start it out at 0
         out[val] = 0

      # increment by one because we've seen it once more
      out[val] += 1

print out
于 2012-04-24T18:29:50.667 に答える