Python 打印字典中的键值对
Python中的字典是一种存储键值对集合的数据结构。与其他数据结构不同,字典在特定位置包含两个值。字典是有序的、可变的,并且不允许重复元素的集合。
- 通过将多个元素序列放置在大括号{ }中,并用逗号(,)进行分隔,可以创建一个字典。字典保存了值对,其中一个是键,另一个是对应的值。
-
字典中的值可以是任何数据类型,并且可以重复,这意味着多个键可以有相同的值,而键不能重复且必须是唯一的。字典中的键是区分大小写的。
我们可以通过以下方式声明一个字典:
thisdict = { "first": "Rohan" , "second": "Suresh" , "third": “Raj” }
现在我们知道了什么是字典以及如何声明它,接下来我们将学习如何在Python中打印键和值的方法。
在本文中,我们将学习4种方法来打印字典中的键值对。
使用Python中的”in”运算符
in运算符用于确定给定的值是否是序列(如字符串、数组、列表或元组)的组成元素。
我们可以使用该运算符来遍历字典,然后打印每个迭代器的键和值。
示例
让我们看一个示例:
dict = { 'first' : 'apple' , 'second' : 'orange' , 'third' : 'mango' }
print ("Original dictionary is : " + str(dict))
print ("Dict key-value are : ")
for i in dict :
print( i, "-",dict[i], sep = " ")
输出
上述代码的输出如下:
Original dictionary is : {'first': 'apple', 'second': 'orange', 'third': 'mango'}
Dict key-value are :
first - apple
second - orange
third - mango
使用Python中的列表推导式
列表推导式是一种根据现有列表、元组或字典的值来创建新列表的简洁方式。
示例
在下面的示例中,我们使用了列表推导式的方法来打印字典中的键值对,这与使用for循环的方法类似,但只需用1行代码就可以完成。
dict = { 'first' : 'apple' , 'second' : 'orange' , 'third': 'mango' }
print ("Original dictionary is : " + str(dict))
print (" Dict key-value are : ")
print([ ( key , dict[key] ) for key in dict])
输出
上述代码的输出如下:
Original dictionary is : {'first': 'apple', 'second': 'orange', 'third': 'mango'}
Dict key-value are :
[('first', 'apple'), ('second', 'orange'), ('third', 'mango')]
在Python中使用dict.items()函数
在Python字典中,items()方法用于返回带有所有字典键和值的列表。在本节中,我们将使用items()函数来打印每个迭代器的键和值。
示例
在下面的代码中,我们使用in运算符遍历字典,并在每次迭代时打印键和值。
dict = { 'first' : 'apple' , 'second' : 'orange' , 'third' : 'mango' }
print ("Original dictionary is : " + str(dict))
print ("Dict key-value are : ")
for key, value in dict.items():
print (key, value)
输出
上述代码的输出结果如下所示:
Original dictionary is : { ‘first’ : ‘apple’ , ‘second’ : ‘orange’ , ‘third’ : ‘mango’ }
Dict key-value are :
first apple
second orange
third mango
总结
在这篇文章中,我们了解了Python中的字典是什么以及我们可以在哪里使用字典。我们了解了在字典中访问键和值对的不同方法以及如何打印它们。我们了解了三种不同的方法来打印键值对。
第一种方法是使用Python的in操作符并通过循环遍历字典来同时访问键和值对并打印它们。第二种方法是使用列表推导式方法,在一行中写入一个for循环。第三种方法涉及使用dict.items()函数在每个迭代中获取键值对并打印它们。
以上每种方法的时间复杂度为O(n),其中n是字典的长度。