similar keys in dictionary in python by R4R Team

- In dictionary of python contains two things i.e. keys and values.
- It is possible to have the multiple values for one key in dictionary but it is not possible to put multiple keys for one value.
- When we try to make multiple similar keys for different values then it gives a warning like dictionary key 'keyname' repeated for different values. but it not give any error in program.

Example

d={1:"one",1:"two"}
- here we have a two keys with same name so dictionary bydefault choose the last key and their values.


program-

d={1:"one",1:"two"}
print(d,d[1])

d={1:"one",1:"two",1:"three"}
print(d,d[1])

d={1:1,1:2,1:3}
print(d,d[1])


output-

{1: 'two'} two
{1: 'three'} three
{1: 3} 3


-In this program, we have a different example of dictionary, one of them are {1:"one",1:"two"}, here we have a two keys of same name '1', so dictionary contain only one key and choose the last one that's by dictionary become {1:"two"}, similary other dictionary works for same keys.

- If we want to store different values for one type of key or want to print above dictionary like this {1:['one','two']} then instead of doing this, do this thing in following way-


program-

l=["one","two"]
d={1:l}
print(d)


output-

{1: ['one', 'two']}




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!