[Tutor] Merging dictionaries
Lie Ryan
lie.1296 at gmail.com
Thu Aug 7 15:33:28 CEST 2008
> Message: 4
> Date: Wed, 6 Aug 2008 21:59:40 +0200
> From: "Norman Khine" <norman at khine.net>
> Subject: [Tutor] Merging dictionaries
> To: tutor at python.org
> Message-ID:
> <9c2c8ffb0808061259u2a655231t54b79b1eb445be7c at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
>
> Hello,
> I am trying to figure out the best way to add results from a poll
> module that I
> have working, but am a bit stuck and can't see on how to add the total
> responses
> submitted by the user.
>
> So far I have an output which puts in a list all the user's responses,
> such as
>
> responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1,
> 3]} .... ]
>
> Is this an efficient way to do this, say for example I have 1000's of
> responses?
>
> What is the best way to append value items of dictionaries, such that:
>
> responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0, 1,
> 3]}]
>
> is transformmed into:
>
> answered = {'a1': [0, 1], 'a2': [1, 2, 3, 0, 1, 3]}
>
> I have tried this:
>
> Type "help", "copyright", "credits" or "license" for more information.
> >>> ret = {}
> >>> myvalues = []
> >>> responses = [{'a1': [1], 'a2': [1, 2, 3]}, {'a1': [0], 'a2': [0,
> 1, 3]}]
> >>> for response in responses:
> mykeys = []
> for answer in response.items():
> mykeys.append(answer[0])
> for key in mykeys:
> if not ret.has_key(key):
> ret[key] = []
> else:
> ret[key].append(answer[1])
>
> >>> print ret
> {'a1': [[1, 2, 3], [0], [0, 1, 3]], 'a2': [[0, 1, 3]]}
>
> But is not correct ;'(
You'd want list.extend, not list.append. There is slight difference
between list.extend and list.append, extend would iterate through the
second list and append each item in the second list to the first list.
>
> And finally, what is the simplest way to count the nummber of
> occurances, so
> that:
>
> answered = {'a1': [0, 1], 'a2': [1, 2, 3, 0, 1, 3]}
>
> returns
>
> totals = {'a1': [{0: 1, 1: 1}], 'a2': [{0: 1, 1: 2, 2: 1, 3: 2}]}
>
>
> I tried this:
>
> ret = {'a1': [[1, 2, 3], [0], [0, 1, 3]], 'a2': [[0, 1, 3]]}
> storage = {}
> for code in ret:
> for answer, x in questions.items():
> for x in x:
> if not storage.has_key(x):
> storage[x] = {'count': 1}
> else:
> storage[x]['count'] += 1
> print storage
>
> But this did not work either.
>
> Cheers
>
> Norman
>
>
More information about the Tutor
mailing list