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.
Curly braces. Passing keyword arguments into dict(), though it works beautifully in a lot of scenarios, can only initialize a map if the keys are valid Python identifiers.
This works:
Copya = {'import': 'trade', 1: 7.8}
Copya = dict({'import': 'trade', 1: 7.8})
This won't work:
Copya = dict(import='trade', 1=7.8)
It will result in the following error:
Copy a = dict(import='trade', 1=7.8)
^
SyntaxError: invalid syntax
The first, curly braces. Otherwise, you run into consistency issues with keys that have odd characters in them, like =.
Copy# Works fine.
a = {
'a': 'value',
'b=c': 'value',
}
# Eeep! Breaks if trying to be consistent.
b = dict(
a='value',
b=c='value',
)
dictionary - How to initialize a dict with keys from a list and empty value in Python? - Stack Overflow
How to create a dictionary where the keys have the same name as variable they are assigned?
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.comBest way to set default value for dictionary
How can I initialize a dictionary in Python?
You can initialize a dictionary in several ways, including using curly braces {}, the dict() constructor, dictionary comprehension, and methods like fromkeys() or zip().
What is a dictionary in Python?
A dictionary in Python is an unordered collection of key-value pairs, where each key is unique and immutable, and each value can be of any data type.
What is the fromkeys() method in Python?
The fromkeys() method creates a dictionary with a set of keys and assigns the same default value to each key.
Videos
dict.fromkeys directly solves the problem:
Copy>>> dict.fromkeys([1, 2, 3, 4])
{1: None, 2: None, 3: None, 4: None}
This is actually a classmethod, so it works for dict-subclasses (like collections.defaultdict) as well.
The optional second argument, which defaults to None, specifies the value to use for the keys. Note that the same object will be used for each key, which can cause problems with mutable values:
Copy>>> x = dict.fromkeys([1, 2, 3, 4], [])
>>> x[1].append('test')
>>> x
{1: ['test'], 2: ['test'], 3: ['test'], 4: ['test']}
If this is unacceptable, see How can I initialize a dictionary whose values are distinct empty lists? for a workaround.
Use a dict comprehension:
Copy>>> keys = [1,2,3,5,6,7]
>>> {key: None for key in keys}
{1: None, 2: None, 3: None, 5: None, 6: None, 7: None}
The value expression is evaluated each time, so this can be used to create a dict with separate lists (say) as values:
Copy>>> x = {key: [] for key in [1, 2, 3, 4]}
>>> x[1] = 'test'
>>> x
{1: 'test', 2: [], 3: [], 4: []}