python
Add items to dictionary in python
We can add a new item to the dictionary by creating a new key and assigning some value to it.
# 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'}
We are using update() function to add new key-value pair in the dictionary(subject). We have added code key and assigned a value E01 to it
Was this helpful?
Similar Posts
- Add two list items with their respective index in python
- Add items to list in Python
- [Python] Using comprehension expression to convert list of dictionaries to nested dictionary
- Remove a key from a dictionary Python
- Sort list and dictionary in python
- Check if a key exist in a dictionary Python
- Convert pandas DataFrame to python collection - dictionary