pathon字典遍历的方法举例
有两种实现字典遍历的方法,下面举例说明
方法1.
dic1 = {'Europe':{'man':'Guido','woman':'girl'}, 'Asia':{'man':'Gongzhen','woman':'Xudan'} } # for i in dic1: # print(i,dic1[i]) for i in dic1.items(): print(i)
方法2.
dic1 = {'Europe':{'man':'Guido','woman':'girl'}, 'Asia':{'man':'Gongzhen','woman':'Xudan'} } for i in dic1: print(i,dic1[i]) # for i in dic1.items(): # print(i)
两种方法得到的结果相同,如下:
3. 还可以用两个变量分别存键和值
dic1 = {'Europe':{'man':'Guido','woman':'girl'}, 'Asia':{'man':'Gongzhen','woman':'Xudan'} } # for i in dic1: # print(i,dic1[i]) # for i in dic1.items(): # print(i) for i,v in dic1.items(): print(i,v)
结果如下: