Use the fromkeys function to initialize a dictionary with any default value. In your case, you will initialize with None since you don't have a default value in mind.
Copyempty_dict = dict.fromkeys(['apple','ball'])
this will initialize empty_dict as:
Copyempty_dict = {'apple': None, 'ball': None}
As an alternative, if you wanted to initialize the dictionary with some default value other than None, you can do:
Copydefault_value = 'xyz'
nonempty_dict = dict.fromkeys(['apple','ball'],default_value)
Answer from codegeek on Stack OverflowUse the fromkeys function to initialize a dictionary with any default value. In your case, you will initialize with None since you don't have a default value in mind.
Copyempty_dict = dict.fromkeys(['apple','ball'])
this will initialize empty_dict as:
Copyempty_dict = {'apple': None, 'ball': None}
As an alternative, if you wanted to initialize the dictionary with some default value other than None, you can do:
Copydefault_value = 'xyz'
nonempty_dict = dict.fromkeys(['apple','ball'],default_value)
You could initialize them to None.
How to create a dictionary where the keys have the same name as variable they are assigned?
Initializing dictionaries from a list of key-value pairs
Also good to note that this works for generators. So you can have:
a = range(10)
b = (x**2 for x in range(10))
dict(zip(a, b))
or
a = ((x, x**2) for x in range(10))More on reddit.com
dict(a)
Can you create a dictionary with a string by mapping the letters to its index?
How to set a default value when a key doesn't exist in a dictionary?
This is the entire purpose of the get() method for dicts.
The method takes two arguments: the first is the key to look for, and the second is the value to return if that key doesn't exist in the dict. (If the key does exist the return value is simply the value associated with that key.)
so my_dict.get("f","Default Value") will do exactly what you're looking for.
Note that this won't actually add the non-existent keys to your dict. If you want to add those keys to your dict you can use defaultdict from the collections module.
https://docs.python.org/3/library/collections.html#defaultdict-objects
More on reddit.com