singular or plural identifier for a dictionary? singular or plural identifier for a dictionary? python python

singular or plural identifier for a dictionary?


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 objectsuser = 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 sensefor 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.


It should be plural because then the program behaves just like you read it aloud. Let me show you why it should not be singular (totally contrived example):

c = Customer(name = "Tony")c.persist()[...]## 500 LOC later, you retrieve the customer list as a mapping from# customer ID to Customer instance.## Singularcustomer = fetchCustomerList()nameOfFirstCustomer = customer[0].namefor c in customer: # obviously it's totally confusing once you iterate    ...# Pluralcustomers = fetchCustomerList()nameOfFirstCustomer = customers[0].name    for customer in customers: # yeah, that makes sense!!    ...

Furthermore, sometimes it's a good idea to have even more explicit names from which you can infer the mapping (for dictionaries) and probably the type. I usually add a simple comment when I introduce a dictionary variable. An example:

# Customer ID => CustomeridToCustomer = {}[...]idToCustomer[1] = Customer(name = "Tony")


I prefer plurals for containers. There's just a certain understandable logic in using:

entries = []for entry in entries:     #Code...