Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper naming conventions for a dictionary in Python

After having someone read through my code, I noticed they got confused by the name of a variable containing a dictionary. The variable was named after the purpose of the keys in the dictionary, not the values, which made them confused. This made me wonder if the "correct" way to name dictionaries is after the keys, values or both?

like image 920
R Z Avatar asked Dec 07 '25 10:12

R Z


2 Answers

It makes more sense to name the dictionary after the values it contains. This is how you would name a list of items. It's also similar to how you would name a function returning a value, namely you choose a name which describes the returned value rather than its parameters. When you see the expression foo["bar"] you want to know what it represents.

Let's say we have a dictionary of words and definitions. If we name the dictionary after the keys it would be something like words["bar"] and if we name it after the values it would be definitions["bar"]. I think most people would agree that the latter makes more sense.

Another strategy is to use key_to_value or value_for_key (or their plural form) which for the example above would be word_to_definition and definition_for_word respectively. Personally I prefer the conciseness of simply definitions.

like image 183
August Karlstrom Avatar answered Dec 09 '25 01:12

August Karlstrom


I think the following link might help you: Python Naming Conventions

In a nutshell: there is no convention, just give your variables proper names so that when people read through your code, they know what its purpose is.

like image 23
Dominik Lovetinsky Avatar answered Dec 09 '25 00:12

Dominik Lovetinsky