4 ways to reverse the dictionary in python (swap the key and value of the dictionary)

1. Dictionary comprehension:

m = {
    
    'a': 1, 'b': 2, 'c': 3, 'd': 4}
res = {
    
    v: k for k, v in m.items()}
print(res)

2. Use compressor:

m = {
    
    'a': 1, 'b': 2, 'c': 3, 'd': 4}
mi = dict(zip(m.values(), m.keys()))
print(mi)

3. Traverse the dictionary:

m = {
    
    'a': 1, 'b': 2, 'c': 3, 'd': 4}
inverted_dict = {
    
    }
for key, value in m.items():
    inverted_dict[value] = key
print(inverted_dict)

4. Combining functions map, reversed:

m = {
    
    'a': 1, 'b': 2, 'c': 3, 'd': 4}
inverted_dict = dict(map(reversed, m.items()))
print(inverted_dict)

Guess you like

Origin blog.csdn.net/qq_34663267/article/details/111183411