Other answers already adressed why this fails, here is a convenient solution that sets a default for if the key is not already present, such that your appending does not fail. The way I read it, you want a dictionary with lists of other dictionaries as values. Imagining a situation such as
Copysomedict = {}
somevar = 0
somevar_name = str(somevar)
key1 = "oh"
value1 = 1
You can do
Copysomedict.setdefault(somevar_name,[]).append({key1,value1})
This will evaluate to
{'0': [{'oh', 1}]}
In other words, change lines of this sort
Copysomedict[some_variables_name] += [{ 'somekey': somevalue }]
Into:
Copysomedict.setdefault(some_variables_name,[]).append({'somekey':somevalue})
I hope this answers your question.
Answer from Banana on Stack OverflowOther answers already adressed why this fails, here is a convenient solution that sets a default for if the key is not already present, such that your appending does not fail. The way I read it, you want a dictionary with lists of other dictionaries as values. Imagining a situation such as
Copysomedict = {}
somevar = 0
somevar_name = str(somevar)
key1 = "oh"
value1 = 1
You can do
Copysomedict.setdefault(somevar_name,[]).append({key1,value1})
This will evaluate to
{'0': [{'oh', 1}]}
In other words, change lines of this sort
Copysomedict[some_variables_name] += [{ 'somekey': somevalue }]
Into:
Copysomedict.setdefault(some_variables_name,[]).append({'somekey':somevalue})
I hope this answers your question.
@Harsha is right.
This:
Copydict[some_variables_name1] += [{ 'key1': value1 }]
Will do:
Copydict[some_variables_name1] = dict[some_variables_name1] + [{ 'key1': value1 }]
Right-Hand-Side needs to be evaluated first so, it will try to lookup:
Copydict[some_variables_name1]
Which will fail.
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
Appending elements to an empty dictionary of lists in Python - Stack Overflow
python - How to add new keys to an empty dictionary as it goes/reads through an input list? - Stack Overflow
Adding Key: Value to Empty Dictionary via For Loop
Why is it common in python to make an empty list or dict first?
Videos
You're checking for the existence of thing in your list, not in your dictionary.
di = {}
stuff = ['sun', 20, 20, 14.3, 'sun', 'Flower']
for thing in stuff: # error was here
if thing not in di:
di[thing] = 1
else:
di[thing] += 1
print(di)
Are you aware of collections.Counter? Counter is a subclass of dict that can do the counting for you.
from collections import Counter
di = Counter(stuff)
print(di)
Your approach is fine if you're still learning, but using Counter is the way to go.
If the task is strictly counting the occurrences then collections.Counter() is the way to go (as @matthias recommends).
A more general way to build a dictionary when you need to alter the key values as you go and where the key may or may not exists is to use the companion collections.defaultdict() or the built in dictionary setdefault().
Your code using setdefault() might look a bit like:
stuff = ['sun', 20, 20, 14.3, 'sun', 'Flower']
di = {}
for thing in stuff:
di[thing] = di.setdefault(thing, 0) + 1
print(di)
I want to stress though that if you are just looking to count the occurrences of items in a list, collections.Counter() is the way to go and the answer by @matthias is what you want to accept.