[Tutor] Dictionary - count values where values are stored as a list
Ricardo Aráoz
ricaraoz at gmail.com
Mon Oct 1 15:25:06 CEST 2007
GTXY20 wrote:
> Hello,
>
> Any way to display the count of the values in a dictionary where the
> values are stored as a list? here is my dictionary:
>
> {'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', 'c'], '4':
> ['a', 'c']}
>
> I would like to display count as follows and I would not know all the
> value types in the values list:
>
> Value QTY
> a 4
> b 3
> c 4
>
> Also is there anyway to display the count of the values list
> combinations so here again is my dictionary:
>
> {'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', 'c'], '4':
> ['a', 'c']}
>
>
> And I would like to display as follows
>
> QTY Value List Combination
> 3 a,b,c
> 1 a,c
>
> Once again all help is much appreciated.
>
> M.
>
>>> D = {'1':['a', 'b', 'c'],
'3':['a', 'b', 'c'],
'2':['a', 'b', 'c'],
'4':['a', 'c']
}
>>> d = {}
>>> for v in reduce(lambda x, y: x+y, [b for a,b in D.iteritems()]):
... d[v] = d.setdefault(v, 0) + 1
...
>>> for k, v in d.iteritems():
... print k, v
...
a 4
c 4
b 3
>>> ld = {}
>>> for v in [''.join(b) for a,b in D.iteritems()]:
... d[v] = d.setdefault(v, 0) + 1
...
>>> for k, v in d.iteritems():
... print v, list(k)
...
1 ['a', 'c']
3 ['a', 'b', 'c']
HTH
More information about the Tutor
mailing list