Call dict with no parameters
Copynew_dict = dict()
or simply write
Copynew_dict = {}
Answer from Jan Vorcak on Stack OverflowInitializer for set, like dict {} and list []
Function to create a dictionary returns empty dictionary when called
Why is it common in python to make an empty list or dict first?
Adding Key: Value to Empty Dictionary via For Loop
Videos
Something I've never understood with python is why it is so common for an empty list to be created and then populated with something in a subsequent (or even more common next) line:
my_list = [] my_list = [i for i in range(1, 21)]
Obviously this is a really really toy example, but I'm consistently finding this in "production" code in multiple places. Is it pythonic? It's basically pure duplication so I doubt it. Is it some hacky "optimisation"? Is it a side effect of the code priorly being a for loop, then turned to a list comprehension but not tidied up right?
I honestly just feel ike I'm missing something key, with the amount of times and variety of places I see this pattern.
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