0
placement = {
    "cross": (50, 120), 
    "circle": (640, 120), 
    "cross": (1066, 120), 
    "circle": (50, 360), 
    "cross": (640, 360), 
    "circle": (1066, 360), 
    "cross": (50, 600), 
    "circle": (640, 600), 
    "cross": (1066, 600)
}

for k in placement.keys():
    print(k)

output : 
cross
circle

I can't seem to understand why only the last two line of my dict is printed and even those two last line do not correspond to the two last lines of my dict.

  • A dictionary has unique keys. You cannot store multiple (key,value) pairs with similar keys – Lexpj Jun 20 '23 at 23:02

4 Answers4

3

dictionary keys must be unique. if you add a print statement you will see that only the last circle and cross are in the dictionary.

placement = {
    "cross": (50, 120), 
    "circle": (640, 120), 
    "cross": (1066, 120), 
    "circle": (50, 360), 
    "cross": (640, 360), 
    "circle": (1066, 360), 
    "cross": (50, 600), 
    "circle": (640, 600), 
    "cross": (1066, 600)
    }

print(placement)
#{'cross': (1066, 600), 'circle': (640, 600)}

you can have a list of dictionaries though.

placement = [
    {"cross": (50, 120)},
    {"circle": (640, 120)},
    {"cross": (1066, 120)},
    {"circle": (50, 360)},
    {"cross": (640, 360)},
    {"circle": (1066, 360)}, 
    {"cross": (50, 600)},
    {"circle": (640, 600)},
    {"cross": (1066, 600)}
    ]

print(placement)
#[{'cross': (50, 120)}, {'circle': (640, 120)}, {'cross': (1066, 120)}, {'circle': (50, 360)}, {'cross': (640, 360)}, {'circle': (1066, 360)}, {'cross': (50, 600)}, {'circle': (640, 600)}, {'cross': (1066, 600)}]
richard
  • 144
  • 3
0

In a python dictionary, keys are unique. In the dictionary you define cross and circle again and again. Each time you define the key again, you will overwrite its previous value.

Perhaps a list of dictionaries is what you are looking for?

placement = [
    {"cross": (50, 120), "circle": (640, 120)},
    {"cross": (1066, 120), "circle": (50, 360)},
    {"cross": (640, 360), "circle": (1066, 360)},
    {"cross": (50, 600), "circle": (640, 600)},
    {"cross": (1066, 600)}
]

for d in placement:
    for key, value in d.items():
        print(f"key: {key} value: {value}")

Output

key: cross value: (50, 120)
key: circle value: (640, 120)
key: cross value: (1066, 120)
key: circle value: (50, 360)
key: cross value: (640, 360)
key: circle value: (1066, 360)
key: cross value: (50, 600)
key: circle value: (640, 600)
key: cross value: (1066, 600)
Matt
  • 973
  • 8
  • 10
0

You have a data issue, a hashmap/dictionary has to have unique keys. In your case you have duplicates.

STK
  • 102
  • 4
  • 11
-1

you can collect all the values corresponding to circle in a list

placement = {
   "cross": [(50, 120), (1066, 120), (640, 360)],
   "circle": [(640, 120), (50, 360), (640, 600)]
}

like this.

Sasha
  • 101
  • 9
Abduley
  • 1
  • 2