2013-10-13 47 views
1

所以這是我的字典的一個片段,我需要幫助創建一個新的字典,基本上是一個直方圖,其中的關鍵是元素的數量和值是從舊字典。Python:字典中的直方圖類型字典

例如1: [27,31]

23: ['20', '10', '3'], 
24: ['19', '16', '14', '6'], 
25: ['16', '5', '9', '24', '18', '15', '11', '12', '14', '5'], 
26: ['22', '15', '10', '6', '5', '4'], 
27: ['4'], 
28: ['27', '26', '20', '9', '22', '9', '25', '7'], 
29: ['15', '26', '16', '24', '4'], 
30: ['25', '16', '18', '21', '19', '4'], 
31: ['2'], 

回答

2

標準的技巧是使用一個defaultdict對於這種直方圖化的:

In [8]: d = {23: ['20', '10', '3'], 
    ...: 24: ['19', '16', '14', '6'], 
    ...: 25: ['16', '5', '9', '24', '18', '15', '11', '12', '14', '5'], 
    ...: 26: ['22', '15', '10', '6', '5', '4'], 
    ...: 27: ['4'], 
    ...: 28: ['27', '26', '20', '9', '22', '9', '25', '7'], 
    ...: 29: ['15', '26', '16', '24', '4'], 
    ...: 30: ['25', '16', '18', '21', '19', '4'], 
    ...: 31: ['2'],} 
In [9]: from collections import defaultdict 
In [10]: hist = defaultdict(list) 
In [11]: for k,v in d.iteritems(): 
    ...:  hist[len(v)].append(k) 
In [12]: hist 
Out[12]: defaultdict(<type 'list'>, {1: [27, 31], 3: [23], 4: [24], 
      5: [29], 6: [26, 30], 8: [28], 10: [25]}) 
0

我認爲這個想法應該是這樣的:

keys = olddic.getallkeys() //which get all the keys 
declare newdic={}; 
iterate each of key in the olddic{ 
    array = olddic[eachkey] 
    newkey = array.size //the length/size 
    store newkey:array into newdic 
} 

我寫的麂皮碼你,但我認爲你的工作是編寫實際的代碼。

使用matplotlib庫創建柱狀圖將節省您的時間!

http://matplotlib.org/