Python 字典翻转输出

2021/8/8 1:36:16

本文主要是介绍Python 字典翻转输出,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

描述:

读入一个字典类型的字符串,反转其中键值对输出。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬
即,读入字典key:value模式,输出value:key模式。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬

输入格式

用户输入的字典格式的字符串,如果输入不正确,提示:输入错误。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬

输出格式‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬

给定字典d,按照print(d)方式输出

方法一:

turn_dic=input()
n={}
try:
    dic=eval(turn_dic)
    for key,value in dic.items():
        n.update({value:key})
    print(n)
except:
    print("输入错误")

知识点描述

1、Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。语法:dict.items()返回值:返回可遍历的(键, 值) 元组数组。
2、Python 字典(Dictionary) update(dict2) 函数把字典dict2的键/值对更新到dict里


方法二

dict=eval(input())  #输入格式:dict = {"a":1,"b":2}
dict_new={}
try:
    for k,v in dict.items():
        dict_new[v]=k #键值互换
    print(dict_new)
except:
    print("输入错误")

方法三

turn_dic=input()
n={}
try:
    dic=eval(turn_dic)
    n=dict([(value,key) for key,value in dic.items()])
    print(n)
except:
    print("输入错误")

知识点描述

使用列表推导式


方法四

def reC(myDict):    # 对字典反转的第二种方法,使用压缩器
    new_dict = dict(zip(myDict.values(), myDict.keys()))
    return new_dict

知识点描述

使用压缩器。
python字典反转的两种方法

真是方法多到惊讶!



这篇关于Python 字典翻转输出的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程