Computer Science
Can you change an element of a sequence or collection? What if a collection is a dictionary? What if a sequence is a string?
Python Dictionaries
CBSE
2 Likes
Answer
Elements of a collection or sequence can be changed only if the collection or sequence is mutable. Hence, for dictionaries, the elements can be changed as dictionaries are mutable but for strings is cannot be changed as strings are immutable.
Example:
>>> d = {1 : 'a', 2: 'b'}
>>> d[1] = 'c'
>>> str = "hello"
>>> str[1] = "python"
Output
{1: 'c', 2: 'b'}
TypeError: 'str' object does not support item assignment
Answered By
2 Likes
Related Questions
Which of the following types qualify to be the keys of a dictionary?
- String
- tuple
- Integer
- float
- list
- dictionary
How do you add key:value pairs to an existing dictionary?
How is indexing of a dictionary different from that of a list or a string?
What do you understand by ordered collection and unordered collection ? Give examples.