update() in dictionary in python by R4R Team

- update() python function of dictionary are able to update the value of the given key.

Syntax-

dict.update(arg)

- Here arg is the pair of keys and values in dictionary form.

Example-

dictionary is d={1:'a',2:'b'}
d.update({1:'z'}) will return {1:'z',2:'b'}

dictionay is d={1:'a',2:'b'}
d.update({3:'y'}) will return {1:'a',2:'b',3:'y'} // that means it create new key if previous not found.


program-

d={1:"pre",2:'b'}
print(d)

d.update({1:'next1'})
print(d)

d.update({2:'next2'})
print(d)

d.update({3:'pre'})
print(d)

d.update({3:'next'})
print(d)


output-

{1: 'pre', 2: 'b'}
{1: 'next1', 2: 'b'}
{1: 'next1', 2: 'next2'}
{1: 'next1', 2: 'next2', 3: 'pre'}
{1: 'next1', 2: 'next2', 3: 'next'}


-In this program, we have a dictionary {1:'pre',2:'b'} then we first update the content of key 1 with 'next' value and print that, similarly we update other keys and values in pair and print them.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!