Python使用for循环遍历字典dict?

在Python中怎么遍历一个字典呢?例如下面的test_dict,怎样遍历所有的key和对应的value呢?

test_dict = {'x': 1, 'y': 2, 'z': 3} 

Python2和Python3遍历dict

代码如下:

test_dict = {'x': 1, 'y': 2, 'z': 3} 
for k in test_dict:
    print('key:{0}, value:{1}'.format(k, test_dict[k])

Python 2遍历字典

代码如下:

test_dict = {'x': 1, 'y': 2, 'z': 3} 
for k, v in test_dict.iteritems():
    print('key:{0}, value:{1}'.format(k, v)

Python 3遍历字典

test_dict = {'x': 1, 'y': 2, 'z': 3} 
for k, v in test_dict.items():
    print('key:{0}, value:{1}'.format(k, v)

By Code问答

发表评论

电子邮件地址不会被公开。 必填项已用*标注

90 − 80 =