1
d ={"A":"h","K":"h","Q":"h","A":"c","K":"c","Q":"c","A":"d","K":"d","Q":"d","A":"s","K":"s","Q":"s"}

print(d)

When I do this, it prints out:

{'A': 's', 'Q': 's', 'K': 's'}

How do I get to print out everything? I have trouble finding out how to write a dictionary with the same values on different keys.

Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
VincFort
  • 1,150
  • 12
  • 29

2 Answers2

5

As others have mentioned in the comments, you cannot have duplicate key's in a dictionary, Python knows to update the existing key with the latest value it's been set to in the duplicate declarations.

You could have a Dictionary that has a tuple (immutable), or list (mutable) as its value.

So if you wanted to have the following coupled information:

'Ah', 'As', 'Ac', 'Ad' , 'Kh', 'Ks' ... 

You could represent that data with:

d = { 'A' : ('h', 's', 'c', 'd'), 'K' : ('h', 's') }

A list value can also work if you wanted to mutate the data within the list. (or set if you do not want duplicate values)

d = { 'A' : ['h', 's', 'c', 'd'], 'K' : ['h', 's'] }

This way you have essentially factored out your common character to be your key.

ospahiu
  • 3,465
  • 2
  • 13
  • 24
  • 2
    Personally I only know the word "collision" in the context of dicts/hashtables when two different keys have the same hash which is not the case here. Here equal keys are used and thus it is expected to replace the accosiated value, otherwise (`d = {}; d["a"] = "a"; d["a"] = "b"; print(d["a"]`) would not do what you expect (i.e. update "a"). So it is not a choice that python "removes duplicate keys" but the only possible thing. – syntonym Jun 28 '16 at 14:57
  • 1
    You are correct, however it's possible to fake duplicate keys in a `dict`: see the link in my comment on the question. – PM 2Ring Jun 28 '16 at 16:37
  • Interesting 'hack' technique @PM2Ring, I'll have to investigate that myself further! – ospahiu Jun 28 '16 at 16:42
0

You could have some other list data structure like this:

my_list = [["A", ["h", "c", "d", "s"]], ["K", ["h", "c", "d", "s"]], ["Q", ["h", "c", "d", "s"]]]

and maybe even convert it into a more usable dictionary, like this:

dic = {}

for item in my_list:
    key = item[0]
    value = item[1]
    dic[key] = value
print(dic)

Output:

{'Q': ['h', 'c', 'd', 's'], 'K': ['h', 'c', 'd', 's'], 'A': ['h', 'c', 'd', 's']}
RoadRunner
  • 25,803
  • 6
  • 42
  • 75