python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python获取字典键对应值

使用Python获取字典键对应值的两种方法

作者:Nurbiya_K

对于字典通过键获得值非常简单,但通过值获得键则需绕些弯子,下面这篇文章主要给大家介绍了关于如何使用Python获取字典键对应值的相关资料,需要的朋友可以参考下

有两种方法

当知道字典的键时:

unit_rooms={ 3:{301:[1,80],302:[1,80],303:[2,90],304:[2,90]},
             4:{401:[1,80],402:[1,80],403:[2,90],404:[2,90]},
             5:{501:[1,80],502:[1,80],503:[2,90],504:[2,90]}
            }
            
 for i in range(3,6):
 	rooms=unit_rooms[i]
 	print(rooms)

运行结果:

当不知道字典的键时:

unit_rooms = {3:{301:[1,80],302:[1,80],303:[2,90],304:[2,90]},
             4:{401:[1,80],402:[1,80],403:[2,90],404:[2,90]},
             5:{501:[1,80],502:[1,80],503:[2,90],504:[2,90]}
            }
 for rooms in unit_rooms.values():
 	print(rooms)

运行结果:

获取字典的值:

for value in DictName.values():
# value的名字可以自行另取
# DictName是要遍历的字典的名称
# .values():是固定的用法

获取键值:

for k,v in DictName.items():
#遍历字典的键值对,k对应键,v对应值
#k,v 的名字可以自己取,DictName是字典名
unit_rooms = {3:{301:[1,80],302:[1,80],303:[2,90],304:[2,90]},
             4:{401:[1,80],402:[1,80],403:[2,90],404:[2,90]},
             5:{501:[1,80],502:[1,80],503:[2,90],504:[2,90]}
            }
 for sub_dict in unit_rooms.values():
# 遍历大字典的值,即小字典sub_dict
    for room,info in sub_dict.items():
        print('房间号:%d,方向:%d,面积:%d'%(room,info[0],info[1]))

运行结果:

方向1代表南北,方向2代表东西

把数字替换掉:

unit_rooms = {3:{301:[1,80],302:[1,80],303:[2,90],304:[2,90]},
             4:{401:[1,80],402:[1,80],403:[2,90],404:[2,90]},
             5:{501:[1,80],502:[1,80],503:[2,90],504:[2,90]}
             }
 for sub_dict in unit_rooms.values():
    for room,info in sub_dict.items():
        dire = ['', '南北', '东西']
        #建立一个列表,第0个元素为空,第1个元素为'南北',第2个元素为'东西'
        print(dire[info[0]])

举例:

unit_rooms = {3:{301:[1,80],302:[1,80],303:[2,90],304:[2,90]},
             4:{401:[1,80],402:[1,80],403:[2,90],404:[2,90]},
             5:{501:[1,80],502:[1,80],503:[2,90],504:[2,90]}
             }
 for sub_dict in unit_rooms.values():
    for room,info in sub_dict.items():
        dire = ['', '南北', '东西']
        print('户室号:%d 朝向:%s 面积:%d' % (room,dire[info[0]],info[1]))            

运行结果:

附:字典dic最大值对应的键

步骤:(1)用max()函数找出最大的值maxValue;(2)套用一的自定义函数

def getKey(dic, value):
    if value not in dic.values():
        return None
    result = set()
    for key in dic:
        if dic[key]==value:
            result.add(key)
    return result
 
dic = {'a':2, 'b':1, 'c':10, 'd':10}
 
maxValue=max(dic.values())
result = getKey(dic,maxValue)
 
>> {'c','d'}

总结

到此这篇关于使用Python获取字典键对应值的文章就介绍到这了,更多相关Python获取字典键对应值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文