I want to increase the value after checking whether there is a key in the dict, so please give me some advice

Asked 1 years ago, Updated 1 years ago, 101 views

Dict already exists, and when I have a key, check whether dict[key] is None or not, and

I thought it would work like the code below, but it didn't work, so I'm asking you a question.

    if (my_dict[key] != None):
KeyError: 3
my_dict = {}

if (my_dict[key] != None):
    my_dict[key] = 1
else:
    my_dict[key] += 1

dictionary python

2022-09-22 22:14

1 Answers

If my_dict[key] finds a key that does not exist in dict (my_dict[key]), None is not returned, but KeyError.

So the code is

if key in my_dict:
    my_dict[key] += 1
else:
    my_dict[key] = 1

If you change it like this, it will work as you want.

However, we recommend that you write collections.defaultdict because this is already a Python standard function.

from collections import defaultdict

my_dict = defaultdict(int)
my_dict[key] += 1


2022-09-22 22:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.