'Python match/case using dictionary keys and values
I'm making a pygame game, and whenever I run my code I get the error expected ':'. I am aware that using [ and ] in match/case blocks is used for something else, but how do I get around this issue?
case pygame.KEYDOWN:
match event.key:
case game.controls["pan_up"]:
world_pos[1] -= 1
case game.controls["pan_left"]:
world_pos[0] -= 1
case game.controls["pan_down"]:
world_pos[1] += 1
case game.controls["pan_right"]:
world_pos[0] += 1
Solution 1:[1]
1. You can use .get
example based on your code:
case pygame.KEYDOWN:
match event.key:
case game.controls.get("pan_up"):
world_pos[1] -= 1
case game.controls.get("pan_left"):
world_pos[0] -= 1
case game.controls.get("pan_down"):
world_pos[1] += 1
case game.controls.get("pan_right"):
world_pos[0] += 1
2. You can use dotted dict
it is just a subclassed dict that __getattr__ returns self.get.
there is a package for this here
and if you are not the one that created that dict you can just convert it like this DottedDict({'bar': 2, 'foo': 1})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

