Python中创建字典的几种方法总结(推荐)
1、传统的文字表达式:
>>> d={'name':'Allen','age':21,'gender':'male'} >>> d {'age': 21, 'name': 'Allen', 'gender': 'male'}
如果你可以事先拼出整个字典,这种方式是很方便的。
2、动态分配键值:
>>> d={} >>> d['name']='Allen' >>> d['age']=21 >>> d['gender']='male' >>> d {'age': 21, 'name': 'Allen', 'gender': 'male'}
如果你需要一次动态地建立一个字典的一个字段,那么这种方式比较合适。
字典与列表不同,不能通过偏移量进行复制,只能通过键来读取或赋值,所以也可以这样为字典赋值,当然访问不存在的键会报错:
>>> d[1]='abcd' >>> d {1: 'abcd', 'age': 21, 'name': 'Allen', 'gender': 'male'} >>> d[2] Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> d[2] KeyError: 2
3、字典键值表
>>> c = dict(name='Allen', age=14, gender='male') >>> c {'gender': 'male', 'name': 'Allen', 'age': 14}
因为这种形式语法简单,不易出错,所以非常流行。
这种形式所需的代码比常量少,但是键必须都是字符串才行,所以下列代码会报错:
>>> c = dict(name='Allen', age=14, gender='male', 1='abcd') SyntaxError: keyword can't be an expression
4、字典键值元组表
>>> e=dict([('name','Allen'),('age',21),('gender','male')]) >>> e {'age': 21, 'name': 'Allen', 'gender': 'male'}
如果你需要在程序运行时把键和值逐步建成序列,那么这种方式比较有用。
5、所有键的值都相同或者赋予初始值:
>>> f=dict.fromkeys(['height','weight'],'normal') >>> f {'weight': 'normal', 'height': 'normal'}
以上这篇Python中创建字典的几种方法总结(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持积木网。
详解Python 2.6 升级至 Python 2.7 的实践心得
前言CentOS6.8安装Python2.7.13,因为软件版本上的需求所以考虑将Python升级至2.7.13,加上生产环境还是以RHEL6为主,互联网自动化运维平台大多数也推荐以Pyt
Mac中升级Python2.7到Python3.5步骤详解
下载Python3.5forMac一步步安装安装的默认路径是:/Library/Frameworks/Python.framework/Versions/3.5/强烈建议不要直接sudoln-s(会直接覆盖系统原来的link导致想调用自
Golang与python线程详解及简单实例
Golang与python线程详解及简单实例在GO中,开启15个线程,每个线程把全局变量遍历增加100000次,因此预测结果是15*100000=1500000.varsumintvarccccintvarm*sync.Mutexfun
标签:字典,线程,详解,如果你,键值