user87566
user87566

Reputation: 73

Python: Histogram type dictionary from a dictionary

So this is a snippet of my dictionary, I need help creating a new dictionary that is basically a histogram where the key is the amount of elements and the values are the are the keys from the old dictionary.

e.g. 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'],

Upvotes: 1

Views: 197

Answers (2)

SCV
SCV

Reputation: 416

I think the idea should be like:

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
}

I write the suede code for you, but I think it is your job to write the actual code.

Using matplotlib library to create the histogram will save your days!

http://matplotlib.org/

Upvotes: 0

Bas Swinckels
Bas Swinckels

Reputation: 18488

A standard trick is to use a defaultdict for this kind of histogramming:

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]})

Upvotes: 2

Related Questions