[Tutor] Nested dictionary with defaultdict
Kepala Pening
kepalapening at gmail.com
Wed Apr 16 05:06:44 CEST 2008
count = lambda x: [{y: x.count(y)} for y in set(x)]
y = {}
for key, val in myDict.items():
y[key] = count(val)
print y
{'1': [{'220': 3}], '3': [{'238': 1}, {'220': 1}], '2': [{'238': 4}, {'220':
1}], '5': [{'238': 1}, {'220': 2}], '4': [{'220': 2}], '7': [{'220': 1}],
'6': [{'238': 2}]}
----- Original Message -----
From: GTXY20 <gtxy20 at gmail.com>
To: tutor at python.org
Date: Tue, 15 Apr 2008 21:51:02 -0400
Subject: [Tutor] Nested dictionary with defaultdict
Hi tutors,
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}}
Now I am pretty sure that I need to loop through the first dictionary and
create a defaultdict from the values for each key in that dictionary but at
this point I am having difficulty coming up with the loop.
I am looking for a satrting point or any suggestions.
Many thanks in advance.
GTXY20
More information about the Tutor
mailing list