R Z
R Z

Reputation: 520

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?

Upvotes: 3

Views: 3085

Answers (3)

August Karlstrom
August Karlstrom

Reputation: 11377

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.

Upvotes: 5

baileythegreen
baileythegreen

Reputation: 1194

Maybe share the dictionary to make the question a bit clearer?

I'm not convinced there is a "correct" way to do this (or that that idea really applies to programming in general). Yes, Python has this idea of There should be one--and preferably only one--obvious way to do it., but that doesn't hold for a lot of things.

I'd probably lean towards keys, but the question is complicated by the fact that dictionaries can contain non-uniform data, so the keys might not represent the same sorts of things.

Your best bet is to aim to make your code easy to read and understand—give things names that describe what they are/contain, name functions for what they do, et cetera. The idea of self-documenting code is useful here.

Upvotes: 1

Dominik Lovetinsky
Dominik Lovetinsky

Reputation: 576

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.

Upvotes: 2

Related Questions