5 Useful Tips With Python Dictionaries
1. Create Dictionaries With Keys Specified

When you write a Python script, you may need to define some global variables. However, when you update these variables in your functions somewhere later, you have to be explicit about these variables being global. A trivial example is shown below:

Global variables

I’m not a big fan of this coding pattern involving the use of the global keyword. When you have multiple global keywords across multiple functions, it’s tedious work. Instead, you can use a dictionary object to capture all related variables. In this case, you can update the dictionary directly because it’ll be located by your interpreter globally. Here’s the modified code:

Dictionary of parameters

As you can notice in the code snippet, I use the fromkeys class method to instantiate a dict object. There are a few advantages to using this instantiation method:

Your code is more readable because it’s clear to the readers what parameters you’re using with this script. In this case, we only have param0 and param1 .

and . When you get the values of these keys of the dictionary using the square bracket, you won’t get the KeyError exception because all of the keys that we specified have the None as their initial values, as shown below:
['Yong Cui']
['Programming', 'Technology', 'Artificial Intelligence', 'Python', 'Machine Learning']