On 07/20/2013 06:17 AM, Sunil Tech wrote:
Hi Everyone,

I have a list of dictionaries like

world =
[{'continent':'Asia','continent_code':1,'ocean':'Pacific','country':'India','country_code':1,'state':'Kerala',
'state_pin':500001},
  
{'continent':'Asia','continent_code':1,'ocean':'Pacific','country':'India','country_code':1,'state':'Karnataka',
'state_pin':500002},
  
{'continent':'Africa','continent_code':2,'ocean':'Atlantic','country':'Egypt','country_code':2,'state':'East
Egypt', 'state_pin':700001},
  
{'continent':'Africa','continent_code':2,'ocean':'Atlantic','country':'Egypt','country_code':2,'state':'West
Egypt', 'state_pin':700002},
  
{'continent':'Africa','continent_code':2,'ocean':'Atlantic','country':'Egypt','country_code':2,'state':'North
Egypt', 'state_pin':700003}]


i am trying to to make it in this format

world = [{'continent':'Asia', 'ocean':'Pacific',
  'countries':[{'country':'India',
'states':[{'state':'Kerala', 'state_pin':500001},
  {'state':'Karnataka', 'state_pin':500002}]
}]
  },
{'continent':'Africa', 'ocean':'Atlantic',
  'countries':[{'country':'Egypt',
'states':[{'state':'East Egypt', 'state_pin':700001},
  {'state':'West Egypt', 'state_pin':700002},
{'state':'North Egypt', 'state_pin':700003}]
  }]
}
]


Is this an assignment? If so, it'd be best to tell us the exact assignment statement. Is it to fit existing code that's designed to work with the second format? Or is this a starting place, and subject to change?

In particular, I'd immediately define a namedtuple, and redefine the first list as a list of such named-tuples. Then I'd make an index to such tuples via your two-dimensional dict entries.

If you stick with your present plan, you should realize that there are assumptions built into it. For example, the assumption that a continent has only one ocean -- that all countries within the continent have the same ocean.

Given all that, the simplest approach is to create defaultdict with the default being list. Then each time you add a record to a dict, you ust append to the list; if it's a new key, an empty list is created for you automatically.

both namedtuple and defaultdict are in the collections module.

http://docs.python.org/2/library/collections.html





--
DaveA

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to