Python | 字典(dict)

前面的啰啰嗦嗦:

字典是“键—值对”的无序可变序列,用{ }初始化。

字典的键不允许重复,可以为整数,复数字符串,元组等,但不能为列表、集合或字典。



字典初始化:

a = {} #创建空字典
b = dict()  #创建空字典
c = dict(name = 'Dong',age = 20)
d = dict.fromkeys(['name','age']) #创建值为空的字典
print(a)
print(b)
print(c)
print(d)
{}
{}
{'age': 20, 'name': 'Dong'}
{'age': None, 'name': None}



访问字典的元素:

1、使用”键’访问字典的“值‘,若键不存在,则会报错

print(c['name'])  #键存在
print(c['sex'])  #键不存在
Dong

Traceback (most recent call last):
  File "D:/pythonwork/teast.py", line 9, in <module>
    print(c['sex'])
KeyError: 'sex'

2、使用字典对象的get()方法,键存在时将返回值,否则返回指定值,默认为None

print(c.get('name'))
print(c.get('sex'))
print(c.get('sex','ABC'))
Dong
None
ABC




字典遍历

使用字典对象items()方法可以返回字典的“键-值”对列表

c = dict(name = 'Dong',age = 20,sex='male')
for item in c.items():
    print(item)
print('')
for key,value in c.items():
    print(key,value)
('age', 20)
('name', 'Dong')
('sex', 'male')

('age', 20)
('name', 'Dong')
('sex', 'male')

使用字典对象的keys()方法可以返回字典的“键”列表

c = dict(name = 'Dong',age = 20,sex='male')
for key in c.keys():
    print(key)
print('')
for key in c:
    print(key)
age
name
sex

age
name
sex


使用字典对象的values()方法可以返回字典的“值”列表

c = dict(name = 'Dong',age = 20,sex='male')
for v in c.values():
    print(v)
print('')
print(c.values())
20
Dong
male

[20, 'Dong', 'male']




字典元素的添加和修改

当以“键”为下标为字典中的元素赋值时,若键不存在,则添加新的键,并赋值,若存在,则修改其对应的值

c = dict(name = 'Dong',age = 20,sex='male')
print(c)
c['age']=21
print(c)
c['score']=90
print(c)
{'age': 20, 'name': 'Dong', 'sex': 'male'}
{'age': 21, 'name': 'Dong', 'sex': 'male'}
{'age': 21, 'score': 90, 'name': 'Dong', 'sex': 'male'}

使用字典对象update()方法将另一个字典的“键值对”添加到新字典中

(若存在相同的键,则值以另一个字典的值为准)

d ={'age':30,'score':92}
print(d)
c ={'name':'Dong','age': 20,'sex':'male'}
print(c)
d.update(c)
print(d)
{'age': 30, 'score': 92}
{'age': 20, 'name': 'Dong', 'sex': 'male'}
{'age': 20, 'score': 92, 'name': 'Dong', 'sex': 'male'}




字典元素删除

c ={'name':'Dong','age': 20,'sex':'male','score':95}
print(c)
c.pop('age')  #删除指定元素
print(c)
del c['name']  #删除指定元素
print(c)
c.clear()   #删除字典中所有元素
print(c)
del c   #删除字典
{'age': 20, 'score': 95, 'name': 'Dong', 'sex': 'male'}
{'score': 95, 'name': 'Dong', 'sex': 'male'}
{'score': 95, 'sex': 'male'}
{}


有序字典
import collections
a = dict()
a['a']=1
a['b']=2
a['c']=3
print(a)
print('')
b = collections.OrderedDict()
b['a']=1
b['b']=2
b['c']=3
print(b)
{'a': 1, 'c': 3, 'b': 2}

OrderedDict([('a', 1), ('b', 2), ('c', 3)])



资料参考:《Python程序设计基础》董付国










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值