Q1: Why is a dictionary termed as an unordered collection of objects?
A1: Dictionaries in Python are termed as unordered collections because they do not maintain any order of their elements based on how they are inserted. The order of items in a dictionary is determined by a process known as “hashing”, which allows for rapid access to elements but does not take into account the order of insertion.
Q2: What type of objects can be used as keys in dictionaries?
A2: In Python, any immutable type can be used as a key in a dictionary. This includes primitive types like integers, floats, and strings, as well as immutable collections like tuples. However, mutable types, like lists or other dictionaries, cannot be used as keys.
Q3: Though tuples are immutable type, yet they cannot always be used as keys in a dictionary. What is the condition to use tuples as a key in a dictionary?
A3: While tuples are indeed immutable and can be used as dictionary keys, there’s a condition: the elements of the tuple must also be immutable. Therefore, a tuple that contains a mutable element, like a list, cannot be used as a key in a dictionary.
Q4: Dictionary is a mutable type, which means you can modify its contents ? What all is modifiable in a dictionary? Can you modify the keys of a dictionary?
A4: Yes, dictionaries in Python are mutable, which means you can change their content. You can add new key-value pairs, modify existing values, and remove key-value pairs. However, you cannot change an existing key. Instead, you would need to add a new key with the new value and then delete the old key.