python字典迭代
时间:2020-02-23 14:42:19 来源:igfitidea点击:
在本教程中,我们将看到如何迭代Python中的字典。
我们可以在dict.keys()中用于密钥:迭代字典的键。
for key in dict.keys(): print(key)
我们可以在dict.values()中使用值:迭代字典值。
for key in dict.values(): print(key)
我们可以使用项目()方法来迭代字典的键值对。
for key,value in dict.items(): print(key,":",value)
让我们在举例的帮助下了解。
dict1={1:"one",2:"two",3:"three"} print("Dictionary:",dict1) print("================") print("Printing keys:") print("================") for key in dict1.keys(): print(key) print("================") print("Printing values:") print("================") for value in dict1.values(): print(value) print("============================") print("Printing key-value pairs:") print("============================") for key,value in dict1.items(): print(key,":",value)
输出:
Dictionary: {1: 'one', 2: 'two', 3: 'three'} ================ Printing keys: ================ 1 2 3 ================ Printing values: ================ one two three ============================ Printing key-value pairs: ============================ 1 : one 2 : two 3 : three