Python | How to create a complex dictionary

I want to create a data structure that will be parsed as a JSON object. The output should look like this, and it should be a dynamic data structure.

{"data": [{"type": "locale", "lat": -34.43778387240597, "lon": 150.04799169921876}, {"type": "poi", "lat": -34.96615974838191, "lon": 149.89967626953126}, {"type": "locale", "lat": -34.72271328279892, "lon": 150.46547216796876}, {"type": "poi", "lat": -34.67303411621243, "lon": 149.96559423828126}]} 

I'm afraid in the middle of implementing this data structure, so I expect good ideas.

thanks

+4
source share
3 answers

Your question is incomprehensible, but you probably want something like this:

 >>> r = DataResult() >>> r.add_poi(-34.96615974838191, 149.89967626953126) >>> r.add_locale(-34.72271328279892, 150.46547216796876) >>>r.add_poi(-34.67303411621243, 149.96559423828126) >>> print r {"data": [{"type": "locale", "lat": -34.43778387240597, "lon": 150.04799169921876}, {"type": "poi", "lat": -34.96615974838191, "lon": 149.89967626953126}, {"type": "locale", "lat": -34.72271328279892, "lon": 150.46547216796876}, {"type": "poi", "lat": -34.67303411621243, "lon": 149.96559423828126}]} 

You can create this by creating the DataResult class and overriding the __str__ or __unicode__ .

Your add_poi might look something like this:

 def add_poi(self, lat, lon): self.append(PoiData(lat, lon)) 

where PoiData is another class representing a data record of type "poi", etc.

+3
source

In response to a comment on Mathiasdm, the answer is: Do you mean how to create a dictionary with a list of dictionaries? This can be done as follows:

 dict = {} dict["data"] = [] dict["data"].append({'type': 'poi', 'lat': 123}) dict["data"].append({'type': 'locale', 'lat': 321}) 

Etc.

But if this is really a problem, I would suggest reading the link for lists and dictionaries again: http://docs.python.org/tutorial/datastructures.html

+5
source

What do you mean? If you create a data structure consisting of voice recorders and lists (for example, the one you specified), you can always parse it into a JSON object using the json package .

0
source

Source: https://habr.com/ru/post/1313256/


All Articles