这篇文章主要介绍了怎么使用Python获取字典键对应的值的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇怎么使用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]))
运行结果:
步骤:(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获取字典键对应的值”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。