【流畅的python】03-创建字典的几种方式

python中创建字典的多种方式

>>> # 1. 用键值表的方式创建字典
>>> a = dict(one=1, two=2, three=3)
>>> a
{'three': 3, 'two': 2, 'one': 1}

>>> # 2. 最常用的文字表达式
>>> b = {"one": 1, "two": 2, "three": 3}
>>> b
{'three': 3, 'one': 1, 'two': 2}

>>> # 3. 动态分配键值
>>> c = {}
>>> c["one"] = 1
>>> c["two"] = 2
>>> c["three"] = 3
>>> c
{'three': 3, 'one': 1, 'two': 2}

>>> # 4. 利用zip方法
>>> d = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d
{'three': 3, 'one': 1, 'two': 2}

>>> # 5. 元组键值表
>>> e = dict([("one", 1), ("two", 2), ("three", 3)])
>>> e
{'three': 3, 'one': 1, 'two': 2}

>>> # 6. 字典推导式
>>> dict = [("one", 1), ("two", 2), ("three", 3)]
>>> f = {key: value for key,value in dict}
>>> f
{'three': 3, 'one': 1, 'two': 2}

>>> # 7. d.fromkeys(it, [initial])
>>> # 将迭代器 it 里的元素设置为映射里的键,如果有 initial参数,就把它作为这些键对应的值(默认是 None )
>>> d.fromkeys(["one", "two", "three"], [1, 2, 3])
{'three': [1, 2, 3], 'one': [1, 2, 3], 'two': [1, 2, 3]}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值