Python: Comparing dictionary key with string

Question:

I’m trying to compare the key in a dictionary with a string in Python but I can’t find any way of doing this. Let’s say I have:

dict = {"a" : 1, "b" : 2}

And I want to compare the key of the first index in the dictionary (which is “a”) with with a string. So something like:

if ´Dictionary key´ == "a":
    return True
else:
    return False

Is there a way of doing this? Appreciate all the help I can get.

Asked By: ScandinavianWays

||

Answers:

Python dictionnaries have keys and values accessed using those keys.

You can access the keys as follows, your dict key will be stored in the key variable:

my_dict = {"a" : 1, "b" : 2}
for key in my_dict:
    print(key)

This will print:

a
b

You can then do any comparisons you want:

my_dict = {"a" : 1, "b" : 2}
for key in my_dict:
    if key == "a":
        return True
    else:
        return False

which can be improved to:

my_dict = {"a" : 1, "b" : 2}
print("a" in my_dict.keys())

You can then access the values for each key in your dict as follows:

my_dict = {"a" : 1, "b" : 2}
for key in my_dict:
    print(my_dict[key])

This will print:

1
2

I suggest you read more about dictionaries from the official Python documentation: https://docs.python.org/3.6/tutorial/datastructures.html#dictionaries

Answered By: Adam Jaamour
result = True if "a" in dict.keys() else False
return result

For the example in your question, result will be True.

If you want to go through each keys, indexes won’t help because dictionaries in Python cannot be instead. You can do the following instead:

for key in dict.keys():
    #do something with key 
Answered By: Arjun Kay