What is the best way to implement nested dictionaries?

后端 未结 21 1806
[愿得一人]
[愿得一人] 2020-11-22 00:29

I have a data structure which essentially amounts to a nested dictionary. Let\'s say it looks like this:

{\'new jersey\': {\'mercer county\': {\'plumbers\':          


        
21条回答
  •  终归单人心
    2020-11-22 00:31

    I find setdefault quite useful; It checks if a key is present and adds it if not:

    d = {}
    d.setdefault('new jersey', {}).setdefault('mercer county', {})['plumbers'] = 3
    

    setdefault always returns the relevant key, so you are actually updating the values of 'd' in place.

    When it comes to iterating, I'm sure you could write a generator easily enough if one doesn't already exist in Python:

    def iterateStates(d):
        # Let's count up the total number of "plumbers" / "dentists" / etc.
        # across all counties and states
        job_totals = {}
    
        # I guess this is the annoying nested stuff you were talking about?
        for (state, counties) in d.iteritems():
            for (county, jobs) in counties.iteritems():
                for (job, num) in jobs.iteritems():
                    # If job isn't already in job_totals, default it to zero
                    job_totals[job] = job_totals.get(job, 0) + num
    
        # Now return an iterator of (job, number) tuples
        return job_totals.iteritems()
    
    # Display all jobs
    for (job, num) in iterateStates(d):
        print "There are %d %s in total" % (job, num)
    

提交回复
热议问题