[Tutor] Dictionaries and aggregation

Paul Churchill paul.churchill at cyanfusion.com
Wed Apr 26 00:04:37 CEST 2006




Right think I've got the idea now. Thanks for all contributions on this.


Paul

-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Karl "Pflästerer"
Sent: 25 April 2006 22:28
To: tutor at python.org
Subject: Re: [Tutor] Dictionaries and aggregation

On 25 Apr 2006, paul.churchill at cyanfusion.com wrote:

[...]
> Here's the list I'm starting with: 
>
>>>> for i in rLst:
>>>>     print i, type(i)
>
> server001      alive 17.1%     2 requests/s 14805416 total <type 'str'>
> server001      alive 27.2%     7 requests/s 14851125 total <type 'str'>
> server002      alive 22.9%     6 requests/s 15173311 total <type 'str'>
> server002      alive 42.0%     8 requests/s 15147869 total <type 'str'>
> server003      alive 17.9%     4 requests/s 15220280 total <type 'str'>
> server003      alive 22.0%     4 requests/s 15260951 total <type 'str'>
> server004      alive 18.5%     3 requests/s 15484524 total <type 'str'>
> server004      alive 31.6%     9 requests/s 15429303 total <type 'str'> 
>
> I've split each string in the list, extracted what I want and feed it into

> an empty dictionary. 
>
>>>> rDict ={}
>>>> i = 0
>>>> while i < (len(rLst)):
>>>>     x, y =  rLst[i].split()[0], int(rLst[i].split()[3])
>>>>     rDict[x] = y
>>>>     print x, y, type(x), type(y)
>>>>     i += 1
[...]
> What I'm hoping to be able to do is update the value, rather than replace 
> it,  so that it gives me the total i.e. 

> server001 9		
> server003 10
> server002 14
> server004 20 

This is easily done.

.>>> rdict = {}
.>>> for line in lst:
....     ans = line.split()
....     rdict[ans[0]] = rdict.get(ans[0], 0) + int(ans[3])
.... 
.>>> rdict
.{'server002': 14, 'server003': 8, 'server001': 9, 'server004': 12}

Dictionaries have a get() method, which has an optional second argument,
which gets returned if there is no such key in the dictionary.

   Karl
-- 
Please do *not* send copies of replies to me.
I read the list
_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor




More information about the Tutor mailing list