python中的Dictionary是最常用的集合数据类型之一。它由嘿值对表示。键已编入索引,但值可能未编入索引。有许多python内置函数使在各种python程序中使用字典变得非常容易。在本主题中,我们将看到三个内置方法,即update(),has_key()和fromkeys()
。
方法更新通过将辅助项目与第一个项目合并来将新项目添加到给定字典中。
dict1.update(dict2) Where dict1 and dict2 are the two input dictionaries.
在下面的示例中,我们看到了成对的字典。第二个字典将添加到第一个字典的项目中。但是在第二个字典中,键的名称应该不同,以查看合并的效果。
dict1 = {'Place': 'Delhi', 'distance': 137}; dict2 = {'Temp': 41 }; dict1.update(dict2) print(dict1)
运行上面的代码给我们以下结果-
{'Place': 'Delhi', 'distance': 137, 'Temp': 41}
此方法验证键是否存在于字典中。这是仅python2的功能。此方法在python3中不可用。
dict.has_key(key)
在下面的示例中,我们检查给定词典中是否存在某些键。
dict1 = {'Place': 'Delhi', 'distance': 137}; dict2 = {'Temp': 41 }; print(dict1.has_key('Place')) print(dict2.has_key('Place'))
运行上面的代码给我们以下结果-
输出结果
True False
在这种方法中,我们将值序列转换为字典。我们还可以指定一个值,该值成为每个键的一部分。
dict.fromkeys(seq)
在下面的示例中,我们根据序列创建字典,并向其中添加一个值。
seq = {'Distnace','Temp','Humidity'} dict = dict.fromkeys(seq) print(dict) dict = dict.fromkeys(seq,15) print(dict)
运行上面的代码给我们以下结果-
输出结果
{'Distnace': None, 'Humidity': None, 'Temp': None} {'Distnace': 15, 'Humidity': 15, 'Temp': 15}