
python循环遍历字典
Dictionaries provide simple data types with value and key. Dictionary data may be used in an iteration with for loop. By using for
mechanism we can iterate over dictionary elements easily. In this tutorial, we will look at different ways to iterate over dictionary elements.
字典提供带有值和键的简单数据类型。 字典数据可用于带有for循环的迭代中。 通过使用for
机制,我们可以轻松地遍历字典元素。 在本教程中,我们将研究迭代字典元素的不同方法。
范例字典 (Example Dictionary)
We will use following dictionary type named mydict
in this tutorial.
在本教程中,我们将使用以下名为mydict
字典类型。
mydict={'b': 2, 'a': 1, 'c': 3
用隐式迭代器进行迭代 (Iterate with Implicit Iterator)
Python dictionary type provides an iterator interface where it can be consumed by for
loops. We just need to provide the dictionary in for
loop. This is a shorter implementation of iterate with keys where we do not need to call iterkeys() function . In this example, we will iterate over with keys in mydict
dictionary.
Python字典类型提供了一个迭代器接口, for
循环使用。 我们只需要在for
循环中提供字典即可。 这是使用键进行迭代的较短实现,无需调用iterkeys()函数。 在此示例中,我们将使用mydict
词典中的键进行迭代。
for x in mydict:
print(x)

用键迭代(Iterate with Keys)
Like the previous example, we can specify the iterate keys with keys() function of the dictionary. keys() function will return all keys inside the given dictionary as python list than this list will be iterated with for
loop.
像前面的示例一样,我们可以使用字典的keys()函数指定迭代键。 keys()函数将以python列表的形式返回给定字典中的所有键,而该列表将使用for
循环进行迭代。
for x in mydict.keys():
print(x)
迭代键和值 (Iterate Keys and Values)
We can use functions provided by dictionary data type which will populate both keys and dictionaries in the same step of for
loop. We will use items()
function which will populate key and value in the same step. We will populate keys into k
variable and values into v
variable in each step.
我们可以使用由字典数据类型提供的函数,这些函数将在for
循环的同一步骤中同时填充键和字典。 我们将使用items()
函数在同一步骤中填充键和值。 在每个步骤中,我们将键填充到k
变量中,将值填充到v
变量中。
for k,v in mydict.items():
print(k)
print(v)

仅迭代值(Iterate Only Values)
We can only iterate overvalues without using any key. We will use values() function provided by dictionary type which will populate values in a given dictionary in an iterable format. We will put values of the dictionary in each step into variable v
.
我们只能在不使用任何键的情况下迭代高估值。 我们将使用字典类型提供的values()函数,该函数将以可迭代的格式填充给定字典中的值。 我们将在每个步骤中将字典的值放入变量v
。
for v in mydict.values():
print(v)

python循环遍历字典