Python字典学习

Python字典

创建新的字典

直接赋值

>>> dict1 = {} # 给 dict1 赋初值为空字典
>>> dict1  # 查看 dict1 无内容
{}

通过fromkeys赋值

# 通过 fromkeys 赋初值后,key 部分有内容,Value 部分为 none
>>> dict1.fromkeys((1,2,3))
{1: None, 2: None, 3: None}
# 下面这种方法将 value 部分赋值为 Number
>>> dict1.fromkeys((1,2,3),'Number')
{1: 'Number', 2: 'Number', 3: 'Number'}
# 下列的赋值方法会将列表的内容赋值给字典
>>> dict1.fromkeys((1,2,3),('one','two','three'))
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
# 下面不是修改了,而是建立了新的字典
>>> dict1.fromkeys((1,3),('one','three'))
{1: ('one', 'three'), 3: ('one', 'three')}
# 不会去修改原来的字典,而是建立了新的字典

通过range赋值

# 通过 range 可以一次性赋值多个字典
>>> dict1 = dict1.fromkeys(range(32),'Item')
>>> dict1
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞', 5: '赞', 6: '赞', 7: '赞', 8: '赞', 9: '赞', 10: '赞', 11: '赞', 12: '赞', 13: '赞', 14: '赞', 15: '赞', 16: '赞', 17: '赞', 18: '赞', 19: '赞', 20: '赞', 21: '赞', 22: '赞', 23: '赞', 24: '赞', 25: '赞', 26: '赞', 27: '赞', 28: '赞', 29: '赞', 30: '赞', 31: '赞'}

keys

# keys 是字典的索引
>>> for eachKey in dict1.keys():
    print(eachKey)
0
1
2
...
30
31

values

# values 是字典的项的值
>>> for eachValue in dict1.values():
    print(eachValue)
赞
赞
...
赞
赞

items

# items 是字典的项,包括索引和值
>>> for eachItem in dict1.items():
    print(eachItem)

(0, '赞')
(1, '赞')
...
(30, '赞')
(31, '赞')

get、in

>>> print(dict1[31])
赞
# 通过 get 可以明确的知道字典的项目是否存在
>>> print(dict1.get(31)) # 存在>>> print(dict1.get(32)) # 不存在
None
>>> dict1.get(32,'my') # 不存在时用 my 表示
'my'
>>> 31 in dict1 # 通过 in 可以获得字典中是否存在的信息
True
>>> 32 in dict1
False

clear

# 下面是清空字典
>>> dict1.clear()
>>> dict1
{}

>>> a = {'姓名':'Paul'}
>>> b = a
>>> b
{'姓名': 'Paul'}
# 下面这种方式进行清空,是对字典 a 重新赋值,对字典 b 不能清空
>>> a = {}
>>> a
{}
>>> b # 字典 b 未清空
{'姓名': 'Paul'}
>>> a = {'姓名':'Paul'}
>>> b = a
# 用 clear 方法清空,可以清空字典 b
>>> a.clear()
>>> a
{}
>>> b
{}

copy、id

>>> a = {1:'one',2:'two',3:'three'}
>>> a
{1: 'one', 2: 'two', 3: 'three'}
# b 是通过 copy 复制的字典,c 是通过指向方式建立的字典标签
>>> b=a.copy()
>>> c=a
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> c
{1: 'one', 2: 'two', 3: 'three'}
# 通过指向方式建立的字典标签与原标签具有相同的 id
>>> id(a)
51696000
>>> id(c)
51696000
# 通过 copy 方式建立的 b 标签,具有独立的 id
>>> id(b)
88498944

# 对 c 增加字典元素就是对具有相同 id 的 a 标签指向的内容进行了增加
>>> c[4] = 'four'
>>> c
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
# 而具有独立 id 的 b 标签指向的内容没有变化
>>> b
{1: 'one', 2: 'two', 3: 'three'}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

彖爻之辞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值