Python 中的字典方法(cmp()、len()、items()…)
pythonserver side programmingprogramming
Python 中的字典是最常用的集合数据类型之一。它由两个值对表示。键被索引,但值可能没有。有许多 Python 内置函数使在各种 Python 程序中使用字典变得非常容易。在本主题中,我们将看到三个内置方法,即 cmp()、len() 和 items()。
cmp()
方法 cmp() 根据键和值比较两个字典。它有助于识别重复的字典以及在字典之间进行关系比较。这是 Python2 独有的功能,Python 3 中没有此功能。
语法
cmp(dict1, dict2) 其中 dict1 和 dict2 是两个输入字典。
在下面的例子中,我们看到了两个字典之间的比较。如果它们相等,则结果为 0。如果第一个字典的值较大,则结果为 1;如果第一个字典的值较小,则结果为 -1。
示例
dict1 = {'Place': 'Delhi', 'distance': 137}; dict2 = {'Place': 'Agra', 'distance': 41}; dict3 = {'Place': 'Bangaluru', 'distance': 1100}; dict4 = {'Place': 'Bangaluru', 'distance': 1100}; print "comparison Result : %d" % cmp (dict1, dict2) print "comparison Result : %d" % cmp (dict2, dict3) print "comparison Result : %d" % cmp (dict3, dict4)
运行上述代码得到以下结果:
comparison Result : 1 comparison Result : -1 comparison Result : 0
len()
此方法给出字典的总长度,该长度等于项数。项是键值对。
语法
len(dict)
在下面的例子中,我们看到了字典的长度。
示例
dict1 = {'Place': 'Delhi', 'distance': 137}; dict2 = {'Place': 'Agra', 'distance': 41 ,'Temp': 25}; print("Length of dict1",len(dict1)) print("Length of dict2",len(dict2))
运行上述代码得到以下结果 −
输出
Length of dict1 2 Length of dict2 3
dict.items()
有时我们可能需要将字典的键值对打印为元组对列表。length 方法给出此结果。
语法
Dictionayname.items()
在下面的示例中,我们看到两个字典,并将每个字典中的项目作为元组对获取。
示例
dict1 = {'Place': 'Delhi', 'distance': 137}; dict2 = {'Place': 'Agra', 'distance': 41 ,'Temp': 25}; print(dict1.items()) print(dict2.items())
运行上述代码得到以下结果 −
输出
dict_items([('Place', 'Delhi'), ('distance', 137)]) dict_items([('Place', 'Agra'), ('distance', 41), ('Temp', 25)])