0

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.

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, it really helped me.
I tried to use "!" Operator in if statement and it didn't work, I forgot about operator "not" :((.
2

You can try:

if i not in my_dict:
    ....

Comments

2
my_dict = dict.fromkeys(my_list, 0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.