If you want to create a dictionary in Python with an empty list of keys, there are several ways to do it, but is there a difference between the methods? We need to experiment and analyze the reasons. In this article, we experiment and analyze two methods.
What if you want to create a dictionary in Python whose keys and values are lists, like the following?
{1:[], 2:[], 3:[], 4:[]}
Method 1, Dictionary Constructor
Generated with the dict constructor, which constructs the (key,value) pair
> key = [1, 2, 3, 4] > a = dict([(k,[]) for k in key]) > a {1: [], 2: [], 3: [], 4: []}
Method 2, using fromkeys()
Use the dictionary method fromkeys(key list, default value)
> key = [1, 2, 3, 4] > b = {}.fromkeys(key,[]) > b {1: [], 2: [], 3: [], 4: []}
Comparison of results
Is there any difference between the dictionaries generated by these two methods? Examine it:
> a[1].append(1) > a {1: [1], 2: [], 3: [], 4: []} # Only affects the corresponding key-value list > > b[1].append(1) > b {1: [1], 2: [1], 3: [1], 4: [1]} # All key-value lists are affected
In the above result, it is found that the empty lists generated using the fromkeys() method all have an element added to them. It seems they are the same object.
Cause analysis
As seen above, the empty list in the dictionary generated with the fromkeys( ) method is actually the same object. Why is this so? Because the parameter "[]" passed to the fromkeys( ) function is the same object, and fromkeys( ) puts a shallow copy of that one object in the dictionary.
If this object is mutable, things can go wrong in subsequent operations. If the object creating the dictionary is mutable, you should avoid using fromkeys( )
For more on Python's dictionary method for creating an empty list check out the related links below