[Tutor] Nested dictionary with defaultdict
GTXY20
gtxy20 at gmail.com
Wed Apr 16 05:39:04 CEST 2008
Thanks John and Kent for the guidance.
This following ends up working perfect for me - instead of print to the
console I will just write this to a text file. I will also wrap it in a
function.
from collections import defaultdict
d = {'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'],
'3': ['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], '6':
['238', '238'], '7': ['220']}
for f, b in d.items():
h = defaultdict(int)
for j in b:
h[j]+=1
for k,v in sorted (h.items()):
print ('%s, (%s:%s)' % (f, k, v))
M.
On Tue, Apr 15, 2008 at 10:19 PM, John Fouhy <john at fouhy.net> wrote:
> On 16/04/2008, GTXY20 <gtxy20 at gmail.com> wrote:
> > I currently have a dictionary like the following:
> >
> > {'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'],
> '3':
> > ['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], '6':
> > ['238', '238'], '7': ['220']}
> >
> > I am trying to create a dictionary that would list the current key and a
> > count of the iterations of values within the value list like so:
> >
> > {'1': {'220' : 3}, '2': {'220' : 1}, 2: {238 : 4}, '3': {'220' : 1}, 3:
> {
> > '238' : 1}, '4': {220 : 2}, '5': {'220: 2}, '5': {238 : 1}, '6': {'238'
> :
> > 2}, '7': {'220' : 1}}
> [...]
> > I am looking for a satrting point or any suggestions.
>
> Can you write a function that will take a list and return a dictionary
> with the counts of elements in the list?
>
> i.e. something like:
>
> >>> def countValues(valueList):
> ... # your code goes here
> ...
> >>> countValues(['220', '238', '238', '238', '238'])
> {'238': 4, '220': 1}
>
> P.S. Your sample output is not a valid dictionary...
>
> --
> John.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080415/f9f6dbc1/attachment.htm
More information about the Tutor
mailing list