A logically nested structure, like a student address has a flat number, a floor number (at least).
Now a student has a name which we can easily map from a monolithic address, using, eg, this convention:
address_to_student
or equivalently:
student_by_address
student_by_address = {
"flat 5 floor 4": "sam",
"flat 2 floor 4": "max",
"flat 9 floor 1": "tim",
}
For efficiency (say if "jen" moves in with "max") I might also want to store addresses as a dictionary indexed by floor.
Based on the overwhelming enthusiasm for the _by_
format in the second linked answer, I've gone with that but for nested dictionaries I'm finding it unintuitive.
students_by_flat_by_floor = {
{
"floor 4": {
"flat 5": ["sam"],
"flat 2": ["max", "jen"]
},
"floor 1": {
"flat 9": ["tim"]
},
}
}
Does anyone else find that unreadable? It would be a class if this wasn't python. Being python I'm keen to avoid that boiler plate. Which is why I'm asking the question, is the alternative more readable or pythonic?
floor_to_flat_to_students = ...
My concerns about the (by) former are:
- +It begins by naming the leaf node which is probably what it is required by its clients.
- +It was by far the higher rated answer of the 2 questions I referenced above for non-nested cases.
- -It feels like the first part needs brackets to read properly (students_by_flat)_by_floor
And the (to) latter:
- +It matches the order of keys used to index it.
- +In the non-nested case, linked above and specifically for python it is the best answer.
- -The strengths of the other.