How to invert each key value pair of a dictionary in Python

2 Answers

0 votes
dic = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
 
dic = {val: key for key, val in dic.items()}

print(dic)




'''
run:

{1: 'A', 2: 'B', 3: 'C', 4: 'D'}


'''

 



answered Mar 28, 2023 by avibootz
0 votes
dic = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
 
dic = dict(map(reversed, dic.items()))

print(dic)




'''
run:

{1: 'A', 2: 'B', 3: 'C', 4: 'D'}


'''

 



answered Mar 28, 2023 by avibootz

Related questions

2 answers 163 views
1 answer 149 views
2 answers 175 views
1 answer 132 views
2 answers 188 views
2 answers 121 views
...