Sobes.tech
Junior — Middle

What operations can be performed with keys in a Python dictionary?

sobes.tech AI

Answer from AI

In Python, dictionary keys can be used to perform the following operations:

  • Check for key existence:
    if key in my_dict:
        print("Key exists")
    
  • Get value by key:
    value = my_dict[key]
    # or safely
    value = my_dict.get(key, default_value)
    
  • Add or update key-value pair:
    my_dict[key] = value
    
  • Delete a key:
    del my_dict[key]
    # or
    my_dict.pop(key, default_value)
    
  • Iterate over keys:
    for key in my_dict.keys():
        print(key)
    
  • Get all keys as a list:
    keys_list = list(my_dict.keys())
    
  • Copy dictionary:
    new_dict = my_dict.copy()
    

Keys in a dictionary must be immutable types (e.g., strings, numbers, tuples).