0

I need some help creating an advanced data structure in Python. I haven't been using the language long, but finding it much harder than PHP when it comes to storing data.

At the end of the day, I want my data like this:

data[year][team] = { 'points' : 30, 'yards' : 800 }

Basically, I need to be able to retrieve, add, edit, and delete data in a json object by looking up via a year-team pair. Any ideas?

1
  • 1
    Just nest dictionaries, these can be converted to and from JSON easily with the module of the same name. Commented Sep 6, 2014 at 10:11

1 Answer 1

1

The simplest approach in my opinion is just using a "dictionary of dictionaries".

data = {2014: {'Liverpool': {'points': 30, 'yards': 800}}}

this will allow you to use data[2014]['Liverpool'] to get the {'points': 30, 'yards': 800} dict.

Adding a year:

data.update({2015: ....})

Adding a team to a year:

data[2014].update({'ManU': ...})

Updating a year-team combo:

data[2014]['Liverpool'].update({'points': 33, 'yards': 820})

etc...

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Gabriel! And to delete would be: data[2014]['Liverpool'] = None ?
A better way to do that would be data[2014]["Liverpool"].clear() but that would leave the "Liverpool" key in the dictionary, which might be annoying depending on your logic. Instead you could use data[2014].pop("Liverpool"), and that way the key is also removed from the 2014 dict.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.