[Tutor] Dictionary - count values where values are stored as a list
Alan Gauld
alan.gauld at btinternet.com
Mon Oct 1 09:58:48 CEST 2007
"GTXY20" <gtxy20 at gmail.com> wrote
> 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
Try a list comprehension:
data = [(key, len(D[key]) for key in D]
Printing that out becomes a simple loop:
print "Value\tQTY"
for tup in data:
print "%s\t%s" % tup
> 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']}
>
The same approach should work except you change the tuple values:
data = [(len(D[key]), D[key]) for key in D]
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list