Search code examples
pythoncoding-stylecontainersidentifier

singular or plural identifier for a dictionary?


When naming a container , what's a better coding style:

source = {}
#...
source[record] = some_file

or

sources = {}
#...
sources[record] = some_file

The plural reads more natural at creation; the singular at assignment.

And it is not an idle question; I did catch myself getting confused in an old code when I wasn't sure if a variable was a container or a single value.

UPDATE

It seems there's a general agreement that when the dictionary is used as a mapping, it's better to use a more detailed name (e.g., recordToSourceFilename); and if I absolutely want to use a short name, then make it plural (e.g., sources).


Solution

  • I think that there are two very specific use cases with dictionaries that should be identified separately. However, before addressing them, it should be noted that the variable names for dictionaries should almost always be singular, while lists should almost always be plural.

    1. Dictionaries as object-like entities: There are times when you have a dictionary that represents some kind of object-like data structure. In these instances, the dictionary almost always refers to a single object-like data structure, and should therefore be singular. For example:

       # assume that users is a list of users parsed from some JSON source
       # assume that each user is a dictionary, containing information about that user
      
       for user in users:
           print user['name']
      
    2. Dictionaries as mapping entities: Other times, your dictionary might be behaving more like a typical hash-map. In such a case, it is best to use a more direct name, though still singular. For example:

      # assume that idToUser is a dictionary mapping IDs to user objects
      
      user = idToUser['0001a']
      print user.name
      
    3. Lists: Finally, you have lists, which are an entirely separate idea. These should almost always be plural, because they are simple a collection of other entities. For example:

      users = [userA, userB, userC] # makes sense
      for user in users:
          print user.name           # especially later, in iteration
      

    I'm sure that there are some obscure or otherwise unlikely situations that might call for some exceptions to be made here, but I feel that this is a pretty strong guideline to follow when naming dictionaries and lists, not just in Python but in all languages.