python反转字典的4种方法(字典的key和value对换)

1.字典推导式:

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

2.使用压缩器:

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

3.遍历字典:

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.结合函数map, reversed:

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

猜你喜欢

转载自blog.csdn.net/qq_34663267/article/details/111183411
今日推荐