I'm new to python and have a question about incrementing key values in dictionary! I was able to google around and found the solutions - like get() or defaultdict(). however, I still don't understand the logic behind it. Would really appreciate your help if you can explain to me, thanks!!
So my original code is this:
list = ['a', 'b', 'c', 'd', 'e']
my_dict = {}
for item in list:
my_dict[item] = 1
print(my_dict)
This code throws a keyerror, I understand it's because of the non-existent key value. Here's a solution I attempted:
list = ['a', 'b', 'c', 'd', 'e']
mydict = {}
for item in list:
if item not in mydict.keys():
mydict[item] = 1
else:
mydict[item] = 1
print(mydict)
However, the output doesn't really increment the values and gives me this:
{'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1}
I thought when it loops through each item in the list, it should check the "if" statement every time, so I'm confused why it's not happening here.
Do you know if it's possible to make this work without using any of the function/method I mentioned above? Thank you so much!
Best, Yuen
CodePudding user response:
You are looping through your list so the values you are checking are 'a'
then 'b'
and so on. Each one of those doesn't exist in the dict yet so it enters the if
clause and does: mydict[item] = 1
.
If you want to see the values getting updated you need to go over the same key more than once.
CodePudding user response:
In your list you have items that are unique, if you have elements repeted, you would see what you are trying to do, i.e.:
>>> import random
>>> a_list = ['a', 'b', 'c', 'd', 'e']
>>> my_dict = {}
>>> for item in [random.choice(a_list) for i in range(30)]:
... try:
... my_dict[item] = 1
... except KeyError:
... my_dict[item] = 1
...
>>> my_dict
{'a': 8, 'e': 5, 'd': 4, 'c': 12, 'b': 1}
What is not entirely clear is, if you want to update the "Key value" itself or the associated value of that particular key-value pair.