Can I modify the keys in a dictionary directly for Python?

What are Python best practices for dictionary dict key constants?

  • When using dictionary (dict) keys in Python, there seem to be a few general approaches: some_dict['key_name']     # string constants everywhere some_dict[KeyConstants.key_name]  #  where class KeyConstants: key_name: 'key_name' some_dict[KEY_NAME]    #  with    from some_module import KEY_NAME      # a module level constant 1. 'key_name' has the disadvantage that you're repeating constants throughout your code. It's not DRY. Worse, if you ever go to publish an your API (in the broadest sense) you'll have consumers of your API repeating these constants everywhere, and if you ever want to change 'key_name' to 'better_key_name' it will be a breaking change. 2. This is the typed language, DRY approach, with constants consolidated in one place. Its only disadvantages are that it's ugly, a bit less readable, and more verbose. Pythonic principles primarily prohibit that. It lets you easily change the constant representing the key, since everyone's coding against the variable KeyConstants.key_name. It also works well with IDEs for refactoring. 3. Module level constants are recommended in the PEP 8 style guide. ALL_CAPS_ARE_LOUD and harder to type. This has some of the advantages of both options 1 and 2. What are some other best practices for dict key constants? Which of the above approaches are preferred and when?

  • Answer:

    1 is a bad idea since you can no longer use pylint to check for typos. I use a hybrid of 2 and 3: keep all of the constants in one module, but, instead of importing it directly into the current namespace, import it with a short name. e.g. import constants as c hashtable[c.SOMEKEY] = 10 This has the advantage of making it obvious where the constants are defined, particularly if you have several such files.

Joseph Barillari at Quora Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.