insert both key and value in dictionary in python by R4R Team

- setdefault() is a python dictionary function which insert key and their value simultaneously in the dictionary.

Syntax-

dict.setdefault(key,value)

- Here dict is actual dictionary in which we want to insert data.
- Key is mendatory
- Value is optional, by default it is None.

Example-

dictionary is d={1:'a',2:'b'}
d.setdefault(3,'c') will return {1:'a',2:'b',3:'c'}


program-

d=dict()
print("Enter key and value in dictionary")
d.setdefault(input(),input())

print("Dictionary is",d)

d.setdefault(2,'b')
print("Dictionary is",d)

d.setdefault(3)
print("Dictionary is",d)

d.setdefault(4,'text')
print("Dictionary is",d)

d.setdefault(5,[6,7,8])
print("Dictionary is",d)


output-

Enter key and value in dictionary
1
one
Dictionary is {'1': 'one'}
Dictionary is {'1': 'one', 2: 'b'}
Dictionary is {'1': 'one', 2: 'b', 3: None}
Dictionary is {'1': 'one', 2: 'b', 3: None, 4: 'text'}
Dictionary is {'1': 'one', 2: 'b', 3: None, 4: 'text', 5: [6, 7, 8]}


-In this program, initially we have a empty dictionary by d=dict() then first data we put by input() function,
-then using setdefault() function e insert new keys and values in the dictionary.
- In d.setfault(3), there is only one argument given so it compute as a key and default value is None, so will print 3:None.




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!