Rookie here and I couldn't find a proper explanation for this.
We have a simple dict:
a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
to loop through and access the values of this dict I have to call
for key in a_dict:
print(key, '->', a_dict[key])
I am saying about
a_dict[key]
specifically. Why python use this convention? Where is a logic behind this? When I want to get values of a dictionary I should call it something like
a_dict[value] or a_dict[values] etc
instead (thinking logically).
Could anyone explain it to make more sense please?
edit:
to be clear: why python use a_dict[key] to access dict VALUE instead of a_dict[value]. LOGICALLY.
CodePudding user response:
I think you are misunderstanding some terminology around dictionaries:
In your example, your keys are color
, fruit
, and pet
.
Your values are blue
, apple
, and dog
.
In python, you access your values by calling a_dict[key]
, for example a_dict["color"]
will return "blue"
.
If python instead used your suggested method of a_dict[value]
, you would have to know what your value was before trying to access it, e.g. a_dict["blue"]
would be needed to get "blue"
, which makes very little sense.
As in Feras's answer, try reading up more on how dictionaries work here
CodePudding user response:
according to your question, I think you meant why python does not use index instead of key to reach values in the dict.
Please take note that there are 4 main data container in python, and each for its usage. (there are also other containers like counter and ...)
for example elements of list and tuple is reachable by their indices.
a = [1,2,3,4,5]
print(a[0]) would print 1
but dictionary as its name shows, maps from some objects (keys in python terminology) to some other objects(values in python terminology). so we would call the key instead of index and the output would be the value.
a = { 'a':1 , 'b':2 }
print(a['a']) would print 1
I hope it makes it a bit more clear for you.
CodePudding user response:
Its because, a dictionary in python, maps the keys and values with a hash function internally in the memory.
Thus, to get the value, you've to pass in the key
.
You can sort of think it like indices of the list vs the elements of the list, now to extract a particular element, you would use lst[index]
; this is the same way dictionaries work; instead of passing in index you would've to pass in
the key
you used in the dictionary, like dict[key]
.
One more comparison is the dictionary (the one with words and meanings), in that the meanings are mapped to the words, now you would of course search for the word
and not the meaning
given to the word, directly.
CodePudding user response:
You are searching for a value wich you don't know if it exists or not in the dict, so the a_dict[key] is logic and correct