Python Dictionary | Add data , POP , popitem , update method

Python Dictionary | Add data , POP , popitem ,
update method:
How to add data in dictionary
user_info[‘Branch’] = ‘CSE’print(user_info)             
# OutPut = {‘name’: ‘pramod’, ‘age’: 22, 
‘rollno’: ‘17691a05b9’, ‘class’: ‘B-Tech’,
 ‘Branch’: ‘CSE’}
Pop method
The pop() method removes the item at the given index from the list. The method also returns the removed item.
print(“popped item is “,user_info.pop(‘age’))
print(user_info)             
#OutPut = {‘name’:’pramod’,’rollno’:’17691a05b9′,
 ‘class’: ‘B-Tech’,’Branch’: ‘CSE’}
 Popitem method
Generating a random number has many application in daily life. In a list various functions are supported for the same. A whole library is dedicated in Python to handle random numbers. But sometimes, we need to perform a similar task with dictionary.
popitem() method in dictionary helps to achieve similar purpose. It removes the arbitrary key-value pair from the dictionary and returns it as tuple.
print(user_info.popitem())
OR
print(user_info.popitem(‘Branch’)) 
TypeError: popitem() takes no arguments (1 given)
Update method
It use to replace which is already is used
and add more data into dictionary
Definition and Usage. The update() method inserts the specified items to the dictionary. The specified items can be a dictionary, or an iterable object.
EXAMPLE
print(f’Before to update userinformation: 
{user_info}’)
OUTPUT 
Before to update userinformation: {‘name’: ‘pramod
‘, ‘age’: 22, ‘rollno’: ‘17691a05b9’, 
‘class’: ‘B-Tech’}
more_info={‘name’:’pramod kumar yadav’,’state’:
 ‘Janakpur’,’country’:’Nepal’}
user_info.update(more_info)
print(f’After update user information{user_info}’)
OUTPUT
After update user information {‘name’: 
‘pramod kumar yadav’, ‘age’: 22, ‘rollno’: 
‘17691a05b9’, ‘class’: ‘B-Tech’, ‘state’: 
‘Janakpur’, ‘country’: ‘Nepal’}

Leave a Comment

Your email address will not be published. Required fields are marked *