python-字典-根據值查找鍵(批量處理(如刪除等)所查到的內容)

知道字典的值,找到對應的鍵並處理

值唯一

mydisc = {'key1':'123', 'key2':'234', 'key3':'345'}
get_value = input('請輸入要查值:')
if get_value in mydisc.values():
    print(list(mydisc.keys())[list(mydisc.values()).index(get_value)])
else:
    print('你要查詢的值'+get_value+'不存在')

不唯一

mydisc = {'key1':'123', 'key2':'234', 'key3':'345','key5':'123'}
get_value = input('請輸入要查值:')
if get_value in mydisc.values():
    for a in range(len(mydisc)):
        if list(mydisc.values())[a]==get_value:
            print(list(mydisc.keys())[a])
else:
    print('你要查詢的值'+get_value+'不存在')

不唯一,找到後處理

找到所有的鍵,刪除
不能找一個刪一個
由於刪掉後字典長度變了,但索引a沒變,會超出範圍

mydisc = {'key1':'123', 'key2':'234', 'key3':'345','key5':'123'}
get_value = input('請輸入要查值:')
if get_value in mydisc.values():
    F = []  # 儲存找到的鍵
    for a in range(len(mydisc)):
        if list(mydisc.values())[a] == get_value:
            F.append((list(mydisc.keys())[a]))    # 找到重複把鍵存起來
    # 找到所有的鍵,刪除(不能找一個刪一個,因爲刪掉後字典長度變了,但索引a沒變,會超出範圍)

    for del_fish in F:
        del mydisc[del_fish]       # 刪掉位置重複的小魚
    print(mydisc)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章