Python summary: to add and delete elements in a dictionary


For learning to do changes in, let’s begin by creating two dictionaries:

>>> readbooks = {} # This is empty
>>> sandwich = {'Slices bread': 4,
		'Lettuce leaves': 1,
		'Slices tomato': 2,
		'Tablespoons mayonnaise': 2,
		'Slices prosciutto': 2,
		'Grilled chicken pieces': 'some ones'}

 

If we want to add a pair key-value, we must use the next syntaxis:

dictionary[key] = value
>>> readbooks
{}
>>> readbooks['The Little Prince'] = True
>>> readbooks
{'The Little Prince': True}

And if we create a new key with existing name, the new pair replaces the existing (which can be used for quickly changing the value of a key):

>>> readbooks['The Little Prince'] = False
>>> readbooks
{'The Little Prince': False}

 

If we want to delete a pair:

del dictionary[key]
>>> sandwich
{'Slices bread': 4, 'Tablespoons mayonnaise': 2, 'Lettuce leaves': 1,
'Grilled chicken pieces': 'some ones', 'Slices tomate': 2,
'Slices prosciutto': 2}
>>> del sandwich['Grilled chicken pieces']
>>> sandwich
{'Slices bread': 4, 'Tablespoons mayonnaise': 2, 'Lettuce leaves': 1,
'Slices tomate': 2, 'Slices prosciutto': 2}

 

For deleting a whole dictionary:

del dictionary
>>> del sandwich
>>> sandwich
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sandwich' is not defined
Liked it? Share it! ;)

Be First to Comment

Leave a Reply