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.
Answer from Thomas Wouters on Stack Overflowdict.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: []}
Adding Key: Value to Empty Dictionary via For Loop
How to declare an empty dictionary of empty dictionaries in Python 2.7? - Stack Overflow
"Which creates an empty dictionary?"
How can I remove keys in a dictionary where the value is empty?
Videos
Over the years I've collected a lot of quotes and I am trying to write a script to parse them out into a dictionary so I can use them in another script.
The quotes are always in this format:
> [!quote] Quote by [[Robert Greene]] > Cultivate a fearless approach to life, attack everything with boldness and energy.
So I've created this script to get them and add them to a dictionary:
import re
quote_list = {}
with open('Quotes.md', 'r', encoding='UTF8') as file:
for line in file:
if '[!quote]' in line:
author = re.findall(r'\[\[(.*?)]]', line) # Find [[author]]
author = ' '.join(author) # remove []
quote_list['author'] = author # add to dictionary
elif '>' in line and not '[!quote]' in line:
quote = line.strip('> ').strip('\n') # strip off > and \n
quote_list['quote'] = quote
print(quote_list)However, the final result is only 1 quote (the last quote in the document), so it appears to be overwriting the entry each time. I'm at a loss for what I'm doing wrong so any advice is much appreciated.
As I typed this out I realized that I don't think this is going to keep the authors + quotes together like I had hoped.
Example:
{'author': 'Frank A. Clark', 'quote': "We find comfort among those who agree with us - growth among those who don't"}Update: This is the final solution I landed on. Reading line by line, if the line meets my criteria then I do what I need to for the author and then use next(file) to skip to the next line and pull the quote, finally adding it into a list as a separate dictionary.
https://pastebin.com/nuiT8Nry
You can use collections.defaultdict for a nested dictionary, where you define an initial value of a dictionary
from collections import defaultdict
#Use the initial value as a dictionary
dct = defaultdict(dict)
dct['a']['b'] = 'c'
dct['d']['e'] = 'f'
print(dct)
The output will be
defaultdict(<class 'dict'>, {'a': {'b': 'c'}, 'd': {'e': 'f'}})
You can create empty dict with {}:
d = {}
You can create dict of dict (as values) the way like the first:
d = {
1: {},
2: {}
}
You can modify the dict's value by []:
d = {1: 0}
d[1] = 1
d
{1: 1}
The similar with dict in dict:
d = {
1: {},
2: {}
}
d[1][4] = 5
d
{1: {4: 5}, 2: {}}
If you want to create a dict of dicts according to the list of keys, you can use dict comprehensions:
keys = [1,2,3,4,5]
d = {key: {} for key in keys}
d
{1: {}, 2: {}, 3: {}, 4: {}, 5: {}}