Python Forum
I am confused with the key and value thing - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: I am confused with the key and value thing (/thread-39465.html)



I am confused with the key and value thing - james1019 - Feb-22-2023

responses = {}
polling_active = True

while polling_active:
    name = input("\nWhat is your name? ")
    response = input("Which mountain would you like to climb someday? ")

    responses[name] = response  # <<< I know this line stores the response in the dictionary, is it store the name as a key and response as a value?I am confused by it

    repeat = input("Would you like to let another person respond? (yes/ no) ")
    if repeat == 'no':
        polling_active = False

print("\n--- Poll Results ---")
for name, response in responses.items():
    print(f"{name} would like to climb {response}.")
I know this line stores the response in the dictionary, is it stores the name as a key and response as a value?I am confused by it.


RE: I am confused with the key and value thing - buran - Feb-22-2023

Yes, it does - each name is key and corresponding response - value in the dict


RE: I am confused with the key and value thing - ndc85430 - Feb-22-2023

Yes. Keys are to dicts what indexes (indices) are to lists and tuples.


RE: I am confused with the key and value thing - deanhystad - Feb-22-2023

Lista and arrays are indexed using an integer. Integer indexing is indexing that uses integer values starting at 0 and going up to the number of elments in the list minus 1. Elements appear in the order of the ordinal value of the integer. list_[0] is the first element, list_[1] the second and so on.

Dictionary are indexed using a key. The key can be any hashable type (essentially any non-mutable type). Often these are str objects, but you can use integers, floats, sets, tuples, object methods, functions, classes, ... Order of elements in a dictionary is not important. element[2] may not be "after" element[1] or "before" element[3]. When you print a dictionary, or list the dictionary keys()/values()/items() the order is the order the elements were added to the dictionary.