Now and then I'll write out a literal dictionary and then realize I inadvertently swapped the keys/values:
MY_DICT = {"VALUE1":"KEY1", "VALUE2":"KEY2"} # <- WHOOPS!
Sometimes such a dictionary can be a bit long, and it is a lot of typing to go back and swap all the keys/values.
One way to fix this is to copy the dict to the interpreter and do a:
{v:k for k,v in MY_DICT.values()}
...and copy/paste the result. But of course, this is also a lot of typing.
The following regex in the Find field would capture key/value group pairs for a dictionary with 6 entries:
\{(.*): (.*), (.*): (.*), (.*): (.*), (.*): (.*), (.*): (.*), (.*): (.*)\}
...I can then swap them like this in the Replace field:
{$2: $1, $4: $3, $6: $5, $8: $7, $10: $9, $12: $11}
Is there a more generic way to execute this find/replace? If I can come up with something, I was thinking of adding a custom SwapDict
command to my PyCharm IDE.
(Complicating things, of course, is we probably cannot count on having nice single-spaces after every colon and comma. And the keys/values might also contain colons sometimes! This is the real world, after all.)
Maybe another approach would be to abandon the regex entirely and teach PyCharm a new Alt+Enter trick: take the dict
, swap the keys/values, and replace the literal dict
with the result. I have no idea how to do this.