一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

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

时间:2022-06-25 01:15:27 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下使用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'}

热门栏目