Reputation: 11
I'd like to know, how I could check if a key already exists in a dictionary. I am using the following code:
my_dict = {};
my_list = ["one", "two", "three", "one"];
for i in my_list:
if i in my_dict:
continue;
else:
my_dict[i] = 0;
but I'd like to use "NOT" operator in if statement to remove else operator from it.
Upvotes: 0
Views: 128
Reputation: 2612
This should work:
my_dict = {}
my_list = ["one", "two", "three", "one"]
for i in my_list:
if i not in my_dict:
my_dict[i] = 0
Thus, it will only add the value if the key doesn't exist in the dictionary.
Upvotes: 3