Can we use two or more same keys in a dictionary? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Can we use two or more same keys in a dictionary?

just like joe:24,joe:12,jet:28

10th Feb 2017, 12:54 AM
karlxu
karlxu - avatar
4 Answers
+ 7
yeah
10th Feb 2017, 12:55 AM
Ahri Fox
Ahri Fox - avatar
+ 5
Yes you can, but only the last one entered will remain as part of the dictionary, Take into account the following code: myDict = {"joe": 23, "joe":55, "ben":34} # first element is is changed to 55 by second # our dictionary is actually {"joe": 55, "ben":34} print(myDict["joe"]) # outputs 55 not 23 print(myDict["joe"]) # again outputs 55 not 23 print(myDict["ben"]) # outputs 34 print(len(myDict)) # when checking the length of the dict you get 2 instead of 3
10th Feb 2017, 1:08 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
Yes use a list... myDict = {"Bob":[1,2,3]} you can store multiple values. You can call them by using... myDict["Bob"][0] # output is 1
10th Feb 2017, 2:29 AM
~Q~
~Q~ - avatar
+ 1
can list(d.keys()) out put the joe,joe,ben or joe,ben ?
10th Feb 2017, 8:00 AM
karlxu
karlxu - avatar