I'm not sure how to represent a certain datastructure in Python. It consists of groups and users where each user must be a member of exactly one group and groups should be in turn contained in a container, groups and users will only be used within this container. Furthermore I need random access to groups and users. A JSON representation of example data would look like this:
{
"groupa": {
"name": "groupa",
"description": "bla",
"members": {
"usera": {
"name": "usera",
"age": 38
},
"userb": {
"name": "userb",
"age": 20
}
}
},
"groupb": {
"name": "groupb",
"description": "bla bla",
"members": {
"userc": {
"name": "userc",
"age": 56
}
}
}
}
Simply using nested dict seems unsuited because users and groups all have well defined attributes. Because Groups and Users are only used within the container I came up with a nested class:
class AccountContainer:
class Group:
def __init__(self, container, group):
self.name = group
self.members = {}
self.container = container
self.container.groups[self.name] = self # add myself to container
class User:
def __init__(self, group, user, age=None):
self.name = user
self.age = age
self.group = group
self.group.members[self.name] = self # add myself to group
def __init__(self):
self.groups = {}
def add_user(self, group, username, age=None):
# possibly check if group exists
self.groups[group].members[username] = AccountContainer.User(self.groups[group], username, age=age)
def add_group(self, group):
self.groups[group] = AccountContainer.Group(self, group)
# creating
c = AccountContainer()
c.add_group("groupa")
c.add_user("groupa", "usera")
# access
c.groups["groupa"].members["usera"].age = 38
# deleting
del(c.groups["groupa"].members["usera"])
- How would you represent such a datastructure?
- Is this a reasonable approach?
To me it seems a bit unnatural using a method to create a group or user while otherwise referring to dicts.