Use app×
QUIZARD
QUIZARD
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
161 views
in Information Technology by (178k points)
Can a dictionary have mutable objects as keys?

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

In Python, dictionary keys must be of an immutable data type. Mutable objects, which can be modified after creation, cannot be used as keys in a dictionary. This restriction is in place to ensure that the keys remain stable and do not change during the lifetime of the dictionary.

Common immutable data types that can be used as keys include:

  1. Strings: e.g., 'name', 'age'
  2. Integers: e.g., 1, 42
  3. Tuples: e.g., ('apple', 'orange')

On the other hand, lists, sets, and dictionaries are examples of mutable data types and cannot be used as keys:

# Example with a mutable object as a key (this will raise an error)
my_dict = {[1, 2]: 'value'}
 

Attempting to use a mutable object as a key will result in a TypeError because dictionaries require keys to be hashable and immutable.

If you need to use a collection of mutable objects as a key-like structure, consider using tuples as keys. You can use tuples to represent a fixed sequence of mutable objects and use that tuple as a key in your dictionary. Keep in mind that the order of elements in the tuple matters for uniqueness, as tuples with different orders will be treated as different keys.

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...