To reverse the key-value of a dict

Asked 2 years ago, Updated 2 years ago, 130 views

Dict is map = { 'a': 1, 'b':2 } Flip the key-value when present.

inv_map = { 1: 'a', 2: 'b' } I want to make it like this.

How do I flip a key-value pair?

python dictionary mapping inverse

2022-09-22 22:23

1 Answers

inv_map = {v: k for k, v in map.items()} You can write it as.

The code description is In fork, vin map.items(), k and v receive key and value, respectively Code to save the key-value of {v:k} back in inverted dict format.

dict((v, k) for k, v in map.iteritems()) It has to be written as.

I'll explain the code here, too In fork, vin map.items(), k and v receive key and value, respectively After the key-value of (v,k) is temporarily stored as an inverted generator, The generator is converted back to dict at dict().


2022-09-22 22:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.