Which data type can be used as a key in a dictionary?

Master Python with the PCAP Certification! Explore interactive quizzes and detailed explanations to ensure your exam success. Gain confidence and get certified!

In Python, the keys in a dictionary must be of a type that is hashable, meaning they must be immutable and have a hash value that remains constant throughout their lifetime. Among the options provided, a string is a valid choice because it is an immutable data type. This means that once a string is created, it cannot be changed, making it suitable for use as a dictionary key.

When you use a string as a key in a dictionary, Python computes its hash value, which allows for efficient retrieval of values associated with that key. Since strings are built-in data types that follow these criteria, they can be used reliably as keys in dictionaries.

On the other hand, lists, dictionaries, and sets are mutable data types. This means their contents can change over time, which in turn alters their hash values. Because of this mutability, Python does not allow these types to be used as keys in dictionaries to maintain the integrity and efficiency of key-value retrieval.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy