Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

python dict confusion

Options
  • 20-05-2011 3:21pm
    #1
    Registered Users Posts: 3,745 ✭✭✭


    I'm having a problem getting a handle on python nested dictionaries;


    I'm trying to iterate over a file with the following elements:
    url				HTTP_CODE	RESPONSE_TIME	SIZE_OF_RESPONSE
    /cake/is/good/for/you 		200 	  	        1024 		        123
    /beer/is/really/good/for/you 	200 	  	        1024 		        123
    /cake/is/good/for/you 		401 	  	        1024 		        123
    /cake/is/good/for/you 		502 	  	        1024 		        123
    /eye/see/a/yellow/door 	200 	  	        1024 		        123
    /i/want/it/painted/black 	400 	  	        1024 		        123
    

    I want to create the following dictionary structure for each unique url to iterate over for a report at the end:

    ---><url>--->count=<counter of occurance>
    	|
    	 --->total_time=<sum of response times>
    	|
    	 --->total_bytes=<sum of response bytes>
            |
             ---><response code>=<counter for this code>
            |
             ---><other response code>=<counter for this other code etc>
    


    When I read the file I want to check if the url is in the dict:
    if it is I want to increase the counter, add the time and size to the totals and check if the http code is present (if yes increase its counter if not add it and set counter to 1).
    else
    I want to add the url to the dict set its counter to 1, intialise time and bytes and set the http code counter for the http code found.

    I'll come back with an example of what I have tried shortly after some tea.


Comments

  • Registered Users Posts: 3,745 ✭✭✭laugh


    laugh wrote: »
    .......


    I got this working with
    class AutoVivification(dict):
        """Implementation of perl's autovivification feature."""
        def __getitem__(self, item):
            try:
                return dict.__getitem__(self, item)
            except KeyError:
                value = self[item] = type(self)()
                return value
    
    frequencies = AutoVivification()
    
        if frequencies.has_key(url):
          frequencies[url]['count'] += 1
          frequencies[url]['size'] += size
          frequencies[url]['time'] += time
        else:
          frequencies[url]['count'] = 1
          frequencies[url]['size'] = size
          frequencies[url]['time'] = time
    


Advertisement