Python字典方法 (cmp(),len(),items()……)


Python中的字典是最常用的集合数据类型之一。它由键值对表示。键是有索引的,但值可能没有索引。许多Python内置函数使在各种Python程序中使用字典变得非常容易。在本主题中,我们将看到三个内置方法,即**cmp()、len()和items()**。

cmp()

cmp()方法根据键和值比较两个字典。它有助于识别重复的字典以及进行字典之间的关系比较。此功能仅在Python 2中可用,在Python 3中不可用。

语法

cmp(dict1, dict2)
Where dict1 and dict2 are the two input dictionaries.

在下面的示例中,我们看到成对的字典相互比较。如果它们相等,结果为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)])

更新于:2019年12月20日

1K+ 次浏览

启动您的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.