欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python中创建字典的几种方法总结(推荐)

时间:2021-08-23 09:25:24|栏目: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'}

上一篇:使用 django orm 写 exists 条件过滤实例

栏    目:Python代码

下一篇:使用DataFrame删除行和列的实例讲解

本文标题:Python中创建字典的几种方法总结(推荐)

本文地址:http://www.codeinn.net/misctech/169143.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有