why get(key, value) returns the correct value even if you type in the wrong value into the value spot?
Question:
so I know what this method does, but i am trying to understand why it does this. For example:
dic = {'a':500, 'b':600}
dic.get('a', 5)
#output
500
i would expect this to be invalid. but it seems to just print the correct value instead of the incorrect value i typed. why does this do that, or is there something else happening that i am missing. Thanks!
Answers:
If you read the docs for dict.get you will see that the second argument is meant to be returned if there is no key present in the dictionary.
For example:
my_dict = {"a": 100, "b": 200}
print(my_dict.get("a", 200)) # 100
print(my_dict.get("c", 300)) # 300
print(my_dict["c"]) # raised KeyError
dict.get()
takes a key and optional value parameter, which is returned if the key is not found and does not compare it to the value of the key. I don’t know why you would want to use it like that, but you could use this to get your result:
dic = {'a': 500, 'b': 600}
key, value = 'a', 5
result = dic.get(key)
if result is None or result != value:
print("Key value pair not found.")
so I know what this method does, but i am trying to understand why it does this. For example:
dic = {'a':500, 'b':600}
dic.get('a', 5)
#output
500
i would expect this to be invalid. but it seems to just print the correct value instead of the incorrect value i typed. why does this do that, or is there something else happening that i am missing. Thanks!
If you read the docs for dict.get you will see that the second argument is meant to be returned if there is no key present in the dictionary.
For example:
my_dict = {"a": 100, "b": 200}
print(my_dict.get("a", 200)) # 100
print(my_dict.get("c", 300)) # 300
print(my_dict["c"]) # raised KeyError
dict.get()
takes a key and optional value parameter, which is returned if the key is not found and does not compare it to the value of the key. I don’t know why you would want to use it like that, but you could use this to get your result:
dic = {'a': 500, 'b': 600}
key, value = 'a', 5
result = dic.get(key)
if result is None or result != value:
print("Key value pair not found.")