我的Python成长之路---第二天---Python基础(8)---2016年1月9日(晴)

时间:2022-03-13 12:04:17

数据类型之字典

一、字典简介

字典dict(dictionary),在其他语言中也成为map,使用键-值(key-value)的形式存储和展现,具有极快的查找速度。

字典的定义

d = {'key':value,...}

字典可以嵌套,value也可以使用列表等数据类型

字典通过键获取键所对应的值

d[key]

二、字典常用方法

1、clear(清除字典所有元素)

代码:

 def clear(self): # real signature unknown; restored from __doc__
""" D.clear() -> None. Remove all items from D.
清除所有元素
"""
pass

示例:

>>> dic = {'name':'zhangxiaoyu', 'age':35, 'address':'beijing china'}
>>> dic.clear()
>>> dic
{}

2、copy(浅拷贝)

代码:

 def copy(self): # real signature unknown; restored from __doc__
""" D.copy() -> a shallow copy of D
浅拷贝,返回的是一个新的字典对象
"""
pass

示例:

>>> dic = {'name':'zhangxiaoyu', 'age':35, 'address':'beijing china'}
>>> dic2 = dic.copy()
>>> dic2
{'age': 35, 'address': 'beijing china', 'name': 'zhangxiaoyu'}

注意:拷贝和赋值dic2 = dic完全不一样,等到讲到深浅拷贝的时候再来探讨这个问题

3、fromkeys(创建新的字典对象)

代码:

 @staticmethod # known case
def fromkeys(*args, **kwargs): # real signature unknown
""" Returns a new dict with keys from iterable and values equal to value.
用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值
"""
pass

示例:

>>> dic = dict.fromkeys(['name','age'],10)
>>> dic
{'age': 10, 'name': 10}

4、get(获取键所对应的值)

代码:

 def get(self, k, d=None): # real signature unknown; restored from __doc__
""" D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
获取键所对应的值如果存在返回值,如果不存在返回d所定义的值
k:key
d:默认值,如果不存在返回的值
"""
pass

示例:

>>> dic = {'name':'zhangxiaoyu', 'age':35, 'address':'beijing china'}
>>> dic.get('name')
'zhangxiaoyu'
>>> dic.get('tel','')
''
>>> dic.get('tel')

注意:与d[key]取值不同的是,get方法如果key不存在则返回默认值,如果没定义返回的是None,而d[key]这种方式key不存在则会报错

>>> dic.get('tel')
>>> dic['tel']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'tel'

5、items(返回键值组成的元祖)

代码:

 def items(self): # real signature unknown; restored from __doc__
""" D.items() -> a set-like object providing a view on D's items
返回键值组成的元祖列表,也就是同时返回键和值
"""
pass

示例:

>>> dic = {'name':'zhangxiaoyu', 'age':35, 'address':'beijing china'}
>>> dic.items()
dict_items([('age', 35), ('address', 'beijing china'), ('name', 'zhangxiaoyu')])

6、keys(返回字典的key)

代码:

 def keys(self): # real signature unknown; restored from __doc__
""" D.keys() -> a set-like object providing a view on D's keys
返回字典的所有的key
"""
pass

示例:

>>> dic = {'name':'zhangxiaoyu', 'age':35, 'address':'beijing china'}
>>> dic.keys()
dict_keys(['age', 'address', 'name'])

说明:2.X返回的直接是列表对象,3.X返回的dict_keys对象,但是也能通过in做是否存在的判断或循环

7、pop(删除指定key的元素,并返回key所对应的值)

代码:

 def pop(self, k, d=None): # real signature unknown; restored from __doc__
"""
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
删除指定key的元素,并返回key所对应的值,如果不存在返回默认值
k:key
d:默认值,如果不存在返回的值
"""
pass

示例:

>>> dic = {'name':'zhangxiaoyu', 'age':35, 'address':'beijing china'}
>>> dic.pop('name')
'zhangxiaoyu'
>>> dic
{'age': 35, 'address': 'beijing china'}
>>> dic.pop('tel','')
''

8、popitem(删除元素)

代码

 def popitem(self): # real signature unknown; restored from __doc__
"""
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
删除元素并返回删除的元素key和value组成的元祖
"""
pass

示例:

>>> dic = {'name':'zhangxiaoyu', 'age':35, 'address':'beijing china'}
>>> dic.popitem()
('age', 35)
>>> dic
{'address': 'beijing china', 'name': 'zhangxiaoyu'}

注意:由于字典是无序的,所以使用这个方法删除的不一定是哪个元素,所以慎用

9、setdefault(设置默认值,这个方法要与get方法配合使用相当于get方法的d参数)

代码:

 def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
""" D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
设置默认值,这个方法要与get方法配合使用相当于get方法的d参数,同样也适用于d[key]这种取值方法 """
pass

示例:

>>> dic = {'name':'zhangxiaoyu', 'age':35, 'address':'beijing china'}
>>> dic.setdefault('tel','')
''
>>> dic.get('tel')
''
>>> dic
{'age': 35, 'tel': '', 'address': 'beijing china', 'name': 'zhangxiaoyu'}
>>> dic['tel']
''

感觉完全是设置了一个新的键值对

10、update(将另一个字典的键值添加到当前字典中)

代码:

 def update(self, E=None, **F): # known special case of dict.update
"""
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
将另一个字典的键值添加到当前字典中
不存在的键直接添加,存在的键将被覆盖
"""
pass

示例:

>>> dic = {'name':'zhangxiaoyu', 'age':35, 'address':'beijing china'}
>>> dic2 = {'tel':'','name':'zhangsan'}
>>> dic.update(dic2)
>>> dic
{'age': 35, 'tel': '', 'address': 'beijing china', 'name': 'zhangsan'}

11、values(返回所有的值)

代码:

 def values(self): # real signature unknown; restored from __doc__
""" D.values() -> an object providing a view on D's values
返回字典所有的值
"""
pass

示例:

>>> dic.values()
dict_values([35, 'beijing china', 'zhangxiaoyu'])

说明:2.X返回的直接是列表对象,3.X返回的dict_values对象,但是也能通过in做是否存在的判断或循环