python字典的特性和字典的创建与删除

特性:
1.字典是无序可变的
2.字典由键值对组成,键与值之间用冒号隔开,字典语素之间用逗号隔开

3.字典的键为任意不可变的数据


字典的创建通常有4中方法:

1.把一个字典赋值给一个变量
 
 
>>> a={'apple':'苹果','banana':'香蕉','pear':'梨'}
>>> a{'apple': '苹果', 'banana': '香蕉', 'pear': '梨'}
>>> b={} #空字典赋给b>>> b{}

2.使用zip对象压缩两个列表
>>> keys = ['a', 'b', 'c', 'd']
>>> values = [1, 2, 3, 4]
>>> dictionary = dict(zip(keys, values))
>>> dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>> x = dict() #空字典
>>> x
{}
3. 使用 dict函数 根据给定的键、值创建字典

>>> d = dict(name='xu', age=10)
>>> d
{'age': 10, 'name': 'xu'}    #字典是无序的,这里不必在意他们的顺序

4. 以给定内容为键,创建值为空的字典

>>> adict = dict.fromkeys(['name', 'age', 'sex'])
>>> adict
{'name': None, 'age': None, 'sex': None}
>>> adict = dict.fromvalues(['name', 'age', 'sex'])
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    adict = dict.fromvalues(['name', 'age', 'sex'])
AttributeError: type object 'dict' has no attribute 'fromvalues'
>>> adict = dict.fromvalue(['name', 'age', 'sex'])
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    adict = dict.fromvalue(['name', 'age', 'sex'])
AttributeError: type object 'dict' has no attribute 'fromvalue'
字典的删除通常有4种方法:
1.del 
 
>>> a={'apple':'苹果','banana':'香蕉','pear':'梨'}
>>> a{'apple': '苹果', 'banana': '香蕉', 'pear': '梨'} >>> del a['apple'] #根据键删除对应的值
>>> a{'banana': '香蕉', 'pear': '梨'}
 


 
 
2.pop,与del相似
>>> a
{'banana': '香蕉', 'pear': '梨'}
>>> a.pop('banana')    #根据键删除对应的值
'香蕉'
>>> a
{'pear': '梨'}

3.popitem,随机删除字典中的一对键值对并把次键值对返回

>>> a={'apple':'苹果','banana':'香蕉','pear':'梨'}
>>> a.popitem()    #因为字典中的元素是无序的所以删除的也是一个随机的键值对
('pear', '梨')
>>> a
{'apple': '苹果', 'banana': '香蕉'}
4.clear,删除整个字典,如果把一个一个字典赋给另一个变量,当其中一个变量变化时,另一个也会随之变化
>>> a
{'apple': '苹果', 'banana': '香蕉'}
>>> a.clear()
>>> a
{}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值