Well you could directly substract from the value by just referencing the key. Which in my opinion is simpler.
Copy>>> books = {}
>>> books['book'] = 3
>>> books['book'] -= 1
>>> books
{'book': 2}
In your case:
Copybook_shop[ch1] -= 1
Answer from Christian W. on Stack OverflowUpdate values in a dictionary, from a list, if the value is currently 1
Here's a quick way to update a dictionary with a second dictionary: use the '|=' operator.
Equivalent of dictionary.update() but for appending when value is a collection?
Can a dictionary automatically update another dictionary with a shared key?
Videos
Well you could directly substract from the value by just referencing the key. Which in my opinion is simpler.
Copy>>> books = {}
>>> books['book'] = 3
>>> books['book'] -= 1
>>> books
{'book': 2}
In your case:
Copybook_shop[ch1] -= 1
Copyd = {'A': 1, 'B': 5, 'C': 2}
d.update({'A': 2})
print(d)
Copy{'A': 2, 'B': 5, 'C': 2}
Say I have code like so:
my_dict = {date1:0, date2:1, date3:0, date4:1} my_list = [80, 20]
Is there a way to get output as follows:
new_dict = {date1:0, date2:80, date3:0 date4:20}
I've tried so much at this point but just cannot get it working, is my initial structure the issue? i.e. you're not supposed to use dictionaries like this? Either you can't do this, or there's a fundamental gap in my knowledge preventing me connecting the dots. Or I'm dumb!
TIA
for example, you have a dictionary 'DictA' and you want to update it with all the items from 'DictB'. Instead of looping on the keys, or items of DictB, you can simply:
DictA |= DictB
I use this A LOT, and I'm thankful to the Redditor who mentioned it in one of those long 'share your tips' threads...
I just learned about the update method while doing some work. I had been writing if statements to check if key is in .keys() for so long. Is there an equivalent for "add key: value if not already in dictionary, otherwise update the value"?
For example to replace:
if ind in collection.keys(): collection[ind].append(x) else: collection[ind] = [x]