Python字典键()方法
Python中的Dictionary是只维护插入顺序的数据值的集合,用于像 map 一样存储数据值,与其他只保存单个值作为元素的 Data Types 不同,Dictionary 保存 key: value 对。
Python Dictionary 中的keys()方法,返回一个视图对象,该对象按插入顺序显示字典中所有键的列表。
Syntax: dict.keys()
Parameters: There are no parameters.
Returns: A view object is returned that displays all the keys. This view object changes according to the changes in the dictionary.
示例 #1:
Python3
# Python program to show working
# of keys in Dictionary
# Dictionary with three keys
Dictionary1 = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
# Printing keys of dictionary
print(Dictionary1.keys())
# Creating empty Dictionary
empty_Dict1 = {}
# Printing keys of Empty Dictionary
print(empty_Dict1.keys())
Python3
# Python program to show updation
# of keys in Dictionary
# Dictionary with two keys
Dictionary1 = {'A': 'Geeks', 'B': 'For'}
# Printing keys of dictionary
print("Keys before Dictionary Updation:")
keys = Dictionary1.keys()
print(keys)
# adding an element to the dictionary
Dictionary1.update({'C':'Geeks'})
print('\nAfter dictionary is updated:')
print(keys)
Python3
# Python program to demonstrate
# working of keys()
# initializing dictionary
test_dict = { "geeks" : 7, "for" : 1, "geeks" : 2 }
# accessing 2nd element using naive method
# using loop
j = 0
for i in test_dict:
if (j == 1):
print ('2nd key using loop : ' + i)
j = j + 1
# accessing 2nd element using keys()
print ('2nd key using keys() : ' + test_dict.keys()[1])
输出:
dict_keys(['A', 'B', 'C'])
dict_keys([])
注意:列表中这些键值的顺序可能并不总是相同。示例 #2:显示字典更新的工作原理
Python3
# Python program to show updation
# of keys in Dictionary
# Dictionary with two keys
Dictionary1 = {'A': 'Geeks', 'B': 'For'}
# Printing keys of dictionary
print("Keys before Dictionary Updation:")
keys = Dictionary1.keys()
print(keys)
# adding an element to the dictionary
Dictionary1.update({'C':'Geeks'})
print('\nAfter dictionary is updated:')
print(keys)
输出:
Keys before Dictionary Updation:
dict_keys(['B', 'A'])
After dictionary is updated:
dict_keys(['B', 'A', 'C'])
在这里,当字典更新时,键也会自动更新以显示更改。
实际应用: keys() 可以用来访问字典的元素,就像我们可以访问列表一样,不使用keys(),没有其他机制提供通过索引访问字典键作为列表的方法。这在下面的示例中得到了证明。
示例 #3:演示 keys() 的实际应用
Python3
# Python program to demonstrate
# working of keys()
# initializing dictionary
test_dict = { "geeks" : 7, "for" : 1, "geeks" : 2 }
# accessing 2nd element using naive method
# using loop
j = 0
for i in test_dict:
if (j == 1):
print ('2nd key using loop : ' + i)
j = j + 1
# accessing 2nd element using keys()
print ('2nd key using keys() : ' + test_dict.keys()[1])
输出 :
2nd key using loop : for
TypeError: 'dict_keys' object does not support indexing
注意:第二种方法不起作用,因为Python 3 中的dict_keys不支持索引。