python循环遍历字典_如何循环和遍历Python字典?

python循环遍历字典

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 Iterator 
Iterate with Iterator 
用迭代器迭代

用键迭代(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 Keys and Values 
Iterate Keys and Values 
迭代键和值

仅迭代值(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)
Iterate Only Values
Iterate Only Values
仅迭代值
LEARN MORE  How To Control Python For Loop with Break Statement?
了解更多信息如何使用Break语句控制Python For循环?

翻译自: https://www.poftut.com/loop-iterate-python-dictionary/

python循环遍历字典

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值