Python中的字典?

-1 投票
3 回答
1617 浏览
提问于 2025-04-15 12:19

在Python中,有多少种方法可以遍历字典呢?

3 个回答

0

这是一个链接,指向Python官方文档中的一个部分,主要讲解数据结构和循环技巧。你可以通过这个链接了解如何在Python中使用不同的数据结构,以及如何有效地进行循环操作。

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
...     print k, v
...
gallahad the pure
robin the brave
0

如果我理解你的问题没错的话,你可以用很多种方法来遍历字典。

对于初学者来说,这里有个不错的阅读材料,点击 这里 可以查看。

另外,字典可能不是你最好的选择。提供更多信息会很有帮助,这样也能更好地帮助你。

1

有很多方法可以做到这一点!

testdict = {"bob" : 0, "joe": 20, "kate" : 73, "sue" : 40}

for items in testdict.items():
    print (items)

for key in testdict.keys():
    print (key, testdict[key])

for item in testdict.iteritems():
    print item

for key in testdict.iterkeys():
    print (key, testdict[key])

这些只是其中的一些方法,但它们开始变得比简单的方法复杂一些。所有的代码都经过测试。

撰写回答