Skip to main content

Dictionary Methods

Add a pair

Adding a new pair can be done like indexing (like array), but with the key instead of index.

d = {'key': 'value'}
d['new_key'] = 'new_value'

Remove a pair

Removing can be done like an array, but with the key instead of index.

d = {'key': 'value'}
del d['key']

update()

This method can be used to add new pairs or update existing ones.

d = {'key': 'value'}
d.update({'new_key': 'new_value'})

If the key already exists, the value will be updated.

If it doesn't, a new pair will be added.

get()

This method is used to get the value of a key.

d = {'key': 'value'}
d.get('key')

If the key doesn't exist, it will return None.