python学习(七)字典

 字典是无序可变序列。

 定义字典时,每个元素的键和值用冒号分隔,元素之间用 逗号分隔,所有的元素放在一对大括号“{}”中。

 字典中的键可以为任意不可变数据,比如整数、实数、复 数、字符串、元组等等。

 globals()返回包含当前作用域内所有全局变量和值的字典

 locals()返回包含当前作用域内所有局部变量和值的字典

字典的创建与删除

1.使用=将一个字典赋值给一个变量

>>> a_dict = {'server': 'db.diveintopython3.org', 'database': 'mysql'}
>>> a_dict
{'database': 'mysql', 'server': 'db.diveintopython3.org'}
>>> x = {} #空字典
>>> x
{}

2.使用dict利用已有数据创建字典:

>>> 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='Dong', age=37)
>>> d
{'age': 37, 'name': 'Dong'}

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

>>> adict = dict.fromkeys(['name', 'age', 'sex'])
>>> adict
{'age': None, 'name': None, 'sex': None}

5.可以使用del删除整个字典

字典元素的读取

1.以键作为下标可以读取字典元素,若键不存在则抛出异常

>>> aDict = {'name':'Dong', 'sex':'male', 'age':37}
>>> aDict['name']
'Dong'
>>> aDict['tel'] #键不存在,抛出异常
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
aDict['tel']
KeyError: 'tel'

2.使用字典对象的get方法获取指定键对应的值,并且可以在键不存在的时候返回指定值。

>>> print(aDict.get('address'))
None
>>> print(aDict.get('address', 'SDIBT'))#返回指定值SDIBT
SDIBT
>>> aDict['score'] = aDict.get('score',[])
>>> aDict['score'].append(98)
>>> aDict['score'].append(97)
>>> aDict
{'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}

字典元素的读取

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

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

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

>>> aDict={'name':'Dong', 'sex':'male', 'age':37}
>>> for item in aDict.items(): #输出字典中所有元素
print(item)
('age', 37)
('name', 'Dong')
('sex', 'male')
>>> for key in aDict: #不加特殊说明,默认输出键
print(key)
age
name
sex
>>> for key, value in aDict.items(): #序列解包用法
print(key, value)
age 37
name Dong
sex male
>>> aDict.keys() #返回所有键
dict_keys(['name', 'sex', 'age'])
>>> aDict.values() #返回所有值
dict_values(['Dong', 'male', 37])

字典元素的添加与修改

1.当以指定键为下标为字典赋值时,若键存在,则可以修改 该键的值;若不存在,则表示添加一个键、值对。

>>> aDict['age'] = 38 #修改元素值
>>> aDict
{'age': 38, 'name': 'Dong', 'sex': 'male'}
>>> aDict['address'] = 'SDIBT' #增加新元素
>>> aDict
{'age': 38, 'address': 'SDIBT', 'name': 'Dong', 'sex': 'male'}

2.使用字典对象的update方法将另一个字典的键、值对添加 到当前字典对象

>>> aDict
{'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}
>>> aDict.items()
dict_items([('age', 37), ('score', [98, 97]), ('name', 'Dong'), ('sex', 'male')])
>>> aDict.update({'a':'a','b':'b'})
>>> aDict
{'a': 'a', 'score': [98, 97], 'name': 'Dong', 'age': 37, 'b': 'b', 'sex': 'male'}

3.

 使用del删除字典中指定键的元素

 使用字典对象的clear()方法来删除字典中所有元素

 使用字典对象的pop()方法删除并返回指定键的元素

 使用字典对象的popitem()方法删除并返回字典中的一个元 素

字典应用案例

1.首先生成包含1000个随机字符的字符串,然后统计每个字 符的出现次数。

>>> import string
>>> import random
>>> x = string.ascii_letters + string.digits + string.punctuation
>>> y = [random.choice(x) for i in range(1000)]
>>> z = ''.join(y)
>>> d = dict() #使用字典保存每个字符出现次数
>>> for ch in z:
d[ch] = d.get(ch, 0) + 1

使用collections模块的Counter类可以快速实现这个功能, 并且提供更多功能,例如查找出现次数最多的元素

>>> from collections import Counter
>>> frequences = Counter(z)
>>> frequences.items()
>>> frequences.most_common(1) #出现次数最多的一个字符
[('A', 22)]
>>> frequences.most_common(3)
[('A', 22), (';', 18), ('`', 17)]

有序字典

     Python内置字典是无序的,如果需要一个可以记住元素插 入顺序的字典,可以使用collections.OrderedDict。

>>> x = dict() #无序字典
>>> x['a'] = 3
>>> x['b'] = 5
>>> x['c'] = 8
>>> x
{'b': 5, 'c': 8, 'a': 3}
>>> import collections
>>> x = collections.OrderedDict() #有序字典
>>> x['a'] = 3
>>> x['b'] = 5
>>> x['c'] = 8
>>> x
OrderedDict([('a', 3), ('b', 5), ('c', 8)])

字典推导式

>>> {i:str(i) for i in range(1, 5)}
{1: '1', 2: '2', 3: '3', 4: '4'}
>>> x = ['A', 'B', 'C', 'D']
>>> y = ['a', 'b', 'b', 'd']
>>> {i:j for i,j in zip(x,y)}
{'A': 'a', 'C': 'b', 'B': 'b', 'D': 'd'}
>>>x=[1,2,3,4]
>>>y=['w','y','z','x']
>>>dict={i:j for i,j in zip(x,y)}
>>>dict
{1: 'w', 2: 'y', 3: 'z', 4: 'x'}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值