Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Comparing dictionary key with string

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.

like image 305
ScandinavianWays Avatar asked Oct 15 '25 14:10

ScandinavianWays


1 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

like image 156
Adam Jaamour Avatar answered Oct 18 '25 07:10

Adam Jaamour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!