首先生成一个字典:
In [17]: dic={}
In [18]: dic.fromkeys('abcde',100)
Out[18]: {'a': 100, 'b': 100, 'c': 100, 'd': 100, 'e': 100}
利用for循环遍历字典的k值:
In [21]: for k in dict1:
....: print(k)
....:
a
c
b
e
d
利用for循环遍历字典的 k 值,并打印出 k 值和 values 值:
In [22]: for k in dict1:
print(k),dict1[k]
....:
a 100
c 100
b 100
e 100
d 100
进行格式化输出与 output 美化之后:
In [23]: for k in dict1:
print("%s : %s" % (k,dict1[k]))
....:
a : 100
c : 100
b : 100
e : 100
d : 100
我们也可以使用 items 将字典输出为列表:
In [24]: dict1.it
dict1.items dict1.iteritems dict1.iterkeys dict1.itervalues
In [24]: dict1.items()
Out[24]: [('a', 100), ('c', 100), ('b', 100), ('e', 100), ('d', 100)]
使用 for 循环遍历这个列表为:
In [25]: for i in dict1.items():print i
('a', 100)
('c', 100)
('b', 100)
('e', 100)
('d', 100)
也可以指定两个变量接收值:
In [27]: for i,v in dict1.items():print i,v
a 100
c 100
b 100
e 100
d 100
直接对字典进行访问,不加任何的方法的话,遍历出来的是字典的k值:
In [29]: for i in dict1:print i
a
c
b
e
d
如果想要输出 values 呢,还是可以像前面一样进行取值:
In [30]: for i in dict1:print i,dict1[i]
a 100
c 100
b 100
e 100
d 100
小时候背过的乘法口诀,我们通过 Python 也可以写出来,代码如下:
#!usr/local/python3/bin/python
for i in range(1,10): #指定有多少列
for j in range(1,i+1): #嵌套指定有多少行,
# print("%s * %s = %s" % (j,i,j*i),end=' ')
print("{0} * {1} = {2}".format(j,i,j*i),end=' ')
#格式化输出,当前循环结束之前以空格分割
print("\n") #循环结束重新进入下一个循环的时候进行换行
最后结果如下:
[root@izj6cdhdoq5a5z7lfkmaeaz ~]# python nine.py
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25
1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36
1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49
1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 = 48 7 * 8 = 56 8 * 8 = 64
1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81