python中如何遍历字典
1. 遍历字典的键key
云海天教程网,大量的免费python教程,欢迎在线学习!
①
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for key in d: print(str(key)+':'+str(d[key])) list:[1, 2, 3] 1:123 111:python3 tuple:(4, 5, 6)
相关推荐:《Python教程》
②
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for key in d.keys(): print(key) 1 list 111 tuple
2. 遍历字典的值value
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for value in d.values(): print (value) [1, 2, 3] 123 python3 (4, 5, 6)
3. 遍历字典的项
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for item in d.items(): print(item) ('list', [1, 2, 3]) (1, 123) ('111', 'python3') ('tuple', (4, 5, 6))
4. 遍历字典的key-value
①
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for key,value in d.items(): print(key,value) list [1, 2, 3] 1 123 111 python3 tuple (4, 5, 6)
②
>>> d={'list':[1, 2, 3],1:123,'111':'python3','tuple':(4, 5, 6)} >>> for (key,value) in d.items(): print(key,value) list [1, 2, 3] 1 123 111 python3 tuple (4, 5, 6)
来源:PY学习网:原文地址:https://www.py.cn/article.html