0

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:

  1. +It begins by naming the leaf node which is probably what it is required by its clients.
  2. +It was by far the higher rated answer of the 2 questions I referenced above for non-nested cases.
  3. -It feels like the first part needs brackets to read properly (students_by_flat)_by_floor

And the (to) latter:

  1. +It matches the order of keys used to index it.
  2. +In the non-nested case, linked above and specifically for python it is the best answer.
  3. -The strengths of the other.
John
  • 6,433
  • 7
  • 47
  • 82
  • The structure is in the structure of the data, why would you want to try and reproduce it in the name? – Thierry Lathuille May 30 '20 at 11:02
  • This was a contrived example where the structure of the data could be presented alongside the named identifiers. Now suppose I pass it to many other functions who see only a named parameter. That makes for a lot of code reading that I was hoping convention could obviate. There may also be similarly named structures containing different data, for example `student_by_address` may use some subset of the address, for efficiency, as it does here. – John May 30 '20 at 11:32

1 Answers1

0

In the absence of official guidelines I refer myself to Guido's PEP 8, "A Foolish Consistency is the Hobgoblin of Little Minds"

For un-nested dictionaries, I prefer, student_by_address, the to I felt to be more suggestive of a verb as might befit a function identifier.

For nested dictionaries it has to be, floor_to_flat_to_students.

Would be receptive to arguments against, but I think this captures the spirit of python for anyone contemplating these issues.

John
  • 6,433
  • 7
  • 47
  • 82