search

What is a key in a dictionary?

In a dictionary, a key is an immutable object that is used to uniquely identify and access a corresponding value. Each key in a dictionary must be unique, meaning that no two keys can have the same value. The keys in a dictionary are used to retrieve the associated values.

Some important characteristics of dictionary keys are:

Uniqueness: Dictionary keys must be unique. If you try to assign a new value to an existing key, it will overwrite the existing value.

Immutable: Dictionary keys must be of an immutable data type, meaning they cannot be changed once they are assigned. Commonly used immutable types for keys are strings, numbers, and tuples.

Hashable: Dictionary keys must be hashable, which means they have a hash value that remains constant throughout their lifetime. Immutable types like strings and numbers are hashable by default, while mutable types like lists or dictionaries are not.

Here's an example of a dictionary with keys and their associated values:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

In this example, 'name', 'age', and 'city' are the keys, and 'John', 30, and 'New York' are their corresponding values.

You can access the value associated with a key by using the square bracket notation [] or the get() method:

print(my_dict['name'])  # Output: John
print(my_dict.get('age'))  # Output: 30

Using the key, you can perform various operations like retrieving, modifying, or deleting values in a dictionary.

my_dict['age'] = 31  # Modify value associated with the 'age' key

del my_dict['city']  # Delete the key-value pair with the 'city' key

print(my_dict)  # Output: {'name': 'John', 'age': 31}

Keys play a crucial role in dictionaries as they provide a way to organize and retrieve data based on unique identifiers.

Related Questions You Might Be Interested