Informatics Practices

Suppose

>>> d1 = { 1 : 'one' , 2: 'two' , 3: 'three' , 4: 'four'}
>>> d2 = { 5 :'five', 6:'six' }

Write the output of the following code:

>>> del d1[3] 
>>> print(d1) 
>>> d1.pop(4) 
>>> print(d1) 
>>> d1 [8] =' eight'
>>> print(d1) 
>>> d1.clear() 
>>> print(d1)

Python Dictionaries

1 Like

Answer

{1: 'one', 2: 'two', 4: 'four'}
'four'
{1: 'one', 2: 'two'}
{1: 'one', 2: 'two', 8: ' eight'}
{}

Working

  1. del d1[3]: Removes the key 3 and its corresponding value 'three' from d1. After deletion, d1 contains {1: 'one', 2: 'two', 4: 'four'}.
  2. d1.pop(4): Removes the key 4 and its corresponding value 'four' from d1. After popping, d1 is {1: 'one', 2: 'two'}.
  3. d1[8] = 'eight': Adds a new key-value pair 8: 'eight' to d1. Now d1 becomes {1: 'one', 2: 'two', 8: 'eight'}.
  4. d1.clear(): Clears all key-value pairs from d1, resulting in an empty dictionary {}.

Answered By

3 Likes


Related Questions