跳转到主内容
websoft网络软件专家 - 深耕网络技术,打造实用软件!

介绍三种访问字典的方法

定义字典 dic = {'a':"hello",'b':"how",'c':"you"} 方法一:
for key in dic:   print key,dic[key]   print key + str(dic[key])
结果:
  a hello   ahello   c you   cyou   b how   bhow
细节: print key,dic[key],后面有个逗号,自动生成一个空格 print key + str(dic[key]),连接两个 字符串 ,用的是加号,直接输出,中间不加逗号 方法二:
for (k,v) in dic.items():   print "dic[%s]="%k,v
结果:
 dic[a]= hello   dic[c]= you   dic[b]= how
方法三:
for k,v in dic.iteritems():   print "dic[%s]="%k,v
结果:
  dic[a]= hello   dic[c]= you   dic[b]= how
对比: items()返回的是列表 对象 ,而iteritems()返回的是iterator对象。例如: Python 3.14.3 微软官方的 Python 扩展,是 VS Code 安装量最高的扩展(209M+)。集成 IntelliSense(通过 Pylance)、调试(通过 Python Debugger)、代码检查、格式化、重构和单元测试等功能。支持 Jupyter Notebook、虚拟环境管理和多 Python 版本切换。 下载
print dic.items() #[('a', 'hello'), ('c', 'you'), ('b', 'how')] print dic.iteritems() #
深究:iteritor是迭代器的意思,一次反悔一个数据项,知道没有为止
for i in dic.iteritems():    print i
结果:
('a', 'hello') ('c', 'you') ('b', 'how')
【相关推荐】 1. 特别推荐 : “php程序员工具箱”V0.1版本下载 2. Python免费视频教程 3. Python基础入门之items()方法 4. Python中的item()函数遍历字典的实例 5. Python中items()系列函数的用法详解 6. 在sorted中iteriitems和items不同之处

相关文章