Sergey Bogatov
Sergey Bogatov

Reputation: 11

Adding not existing key to dictionary with if statement (Python)

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

Answers (3)

PaulMcG
PaulMcG

Reputation: 63709

my_dict = dict.fromkeys(my_list, 0)

Upvotes: 2

ebeneditos
ebeneditos

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

Harsha Biyani
Harsha Biyani

Reputation: 7268

You can try:

if i not in my_dict:
    ....

Upvotes: 2

Related Questions