Python中创建字典的几种方法

Python中创建字典的5种方法

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(mostrecentcalllast):

File"<pyshell#9>",line1,in<module>d[2]

Keyerror:212345678

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:keywordcan"tbeanexpression

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"}

原文地址:https://www.weidianyuedu.com/content/2720725386234.html

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值