简体   繁体   中英

Conversing Multilevel Dictionary in Python

So, I'm trying to make a program where I have a dictionary like below. The thing is, the user should be able to add a value to one of the pre-existing dictionaries - either a string or another dictionary. I don't think I'd be having as much trouble except I'd like more dictionaries to be able to added as a value to student, and then more dictionaries into the one made in that, etc. etc. So basically I won't know how many dictionaries are being added and how far down that line goes, so I don't think I can just hard code in to add to that?

Sorry if I'm not making much sense, but the idea is basically that the user would start out at cities and be prompted to add a city. From there, they could either sort of 'go into' cities and add a school, or add an additional city and so on. Just really struggling on how to implement this, and I don't want to use any sort of imports.

I'm pretty new to Python so sorry if this seems really stupid.

cities = {
    "city_1": {
        "school_1": {
            "class_1":{
                "student_1": {
                    "name": "Joe"
                },
                "student_2": {
                    "name": "Tim"
                }
            }
        },
        "school_2": {
            "class_1": {
                "student_1": {
                    "name": "Joe"
                },
                "student_2": {
                    "name": "Tim"
                }
            }
        }
    },
    "city_2": {
            "school_1": {
                "class_1": {
                    "student_1": {
                        "name": "Sarah"
                    },
                    "student_2": {
                        "name": "Jake"
                    }
                },
                "class_1": {
                    "student_1": {
                        "name": "Sarah"
                    },
                    "student_2": {
                        "name": "Jake"
                    }
                }
            }
    }
}

If I understand correctly, you need some way to handle nested dictionaries to perform basic operations. This is not an easy task as you need to write you logic to set, get, delete, and iterate over items.

You can start from Best way to get nested dictionary items , but here it is how you can get an item:

def getitem(d, key):
    for level in key:
        d = d[level]
    return d
>>> d = {"a": {"b": {"c": 0}}}
>>> getitem(d, ("a", "b"))
{"c": 0}
>>> getitem(d, ("a", "b", "c"))
0

How to set an item:

def setitem(d, key, value):
    if not isinstance(key, tuple):
        key = (key,)
    item = d
    for k in key[:-1]:
        item = item.setdefault(k, {})
    item[key[-1]] = value
>>> setitem(d, "b", 2)
>>> d
{'a': {'b': {'c': 0}}, 'b': 2}
>>> setitem(d ("a", "b"), 1)
>>> d
{'a': {'b': 1}, 'b': 2}

If you want an implementation for the other methods that I mentioned check out the NestedDict class from the package ndicts (I am the author). I started from the collections.abc MutableMapping class, imported it and defined my logic of the __getitem__ , __setitem__ , __delitem__ , __iter__ , __len__ methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM