I am new to python and need help to understand this piece of code used to create a dictionary
new_key_lis = [18,23,45]
b= dict([(23,18)])
c = dict(zip(new_key_lis, [None]*len(new_key_lis)))
print(c)
I would like to know about the difference between [None] and None ?
CodePudding user response:
None is the special value for nothing, the sole value of the NoneType type.
[None] is a list that contains exactly one value, and that value is None.
So not only None and [None] and different, but they have different type.
To go one step further, a list can be multiplied with an integer to repeat its elements. For example [1, 2] * 3 is [1, 2, 1, 2, 1, 2]
CodePudding user response:
Here, you have new_key_lis = [18,23,45]. If you want to create a dictionary with the items in it as keys and None as values using the dict() constructor, then since new_key_lis is of length 3, you need a list of Nones of the same length to pass to zip(). That's what you are creating with [None]*len(new_key_lis).
You can get the exact same outcome using
c= dict.fromkeys(new_key_lis)
without the need to work with [None] because dict.fromkeys method creates a new dictionary with keys from the passed sequence (in this case new_key_lis) and values set to a default value (unless otherwise assigned, None).
