python的{}字典操作

一个简单的for语句就能循环字典的所有键,就像处理序列一样:
复制代码
In [1]: d = {'x':1, 'y':2, 'z':3}

In [2]: for key in d:
   ...:     print key, 'corresponds to', d[key]
   ...: 
y corresponds to 2
x corresponds to 1
z corresponds to 3
复制代码

  在python2.2之前,还只能用beys等字典方法来获取键(因为不允许直接迭代字典)。如果只需要值,可以使用d.values代替d.keys。d.items方法会将键-值对作为元组返回,for循环的一大好处就是可以循环中使用序列解包:

In [4]: for key, value in d.items():
   ...:     print key, 'corresponds to', value
   ...: 
y corresponds to 2
x corresponds to 1
z corresponds to 3

注意:字典元素的顺序通常没有定义。换句话说,迭代的时候,字典中的键和值都能保证被处理,但是处理顺序不确定。如果顺序很重要的话,可以将键值保存在单独的列表中,例如迭代前进行排序。

原文地址:https://www.cnblogs.com/chenjianhong/p/4144857.html