# Define new dictionary
subject = {
'name': 'Math',
'marks': '100'
}
# Add new item to dictionary
subject['code'] = 'M01'
print(subject)
# -> {'name': 'Math', 'marks': '100', 'code': 'M01'}
To add an item to the dictionary, you just have to assign the relevant data to the relevant key in a dictionary. This is done by enclosing the key and value in braces.
In the above code snippet
1. We have created a dictionary named subject that contains multiple items.
2. We have created a new key 'code' and assigned a value 'M01' to it.
3. Print the dictionary(subject).
If the key already exists inside the dictionary then its value will be updated.
# Define new dictionary
subject = {
'name': 'English',
'marks': '50'
}
# Add new item using update() function
subject.update({'code': 'E01'})
print(subject)
# -> {'name': 'English', 'marks': '50', 'code': 'E01'}
0 Comments