栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python循环遍历字典

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

python循环遍历字典

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/833699.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号