1、字典类型
1.1什么是字典
字典:Python
内置的数据结构之一,与列表一样是一个 可变序列,以 键值对的方式存储数据,字典是一个 无序的序列。Python
语言中的字典使用大括号{ }
建立,每个元素是一个键值对。“
键值对
”是组织数据的一种重要方式,广泛应用在当代大型信息系统中,如Web
系统。键值对的基本思想是将“值”信息关联一个“键”信息,进而通过键信息找对应的值信息,这个过程叫映射。Python
语言中通过字典类型实现映射。
1.2字典示意图
1.3字典的原理
字典的原理:Python
中的字典是根据key
查找value
所在的位置
1.4创建字典的方式
在 python
中创建一个字典对象,常用的方式有两种。
- 第一种方式,使用花括号
{ }
'''
第一种方式,使用花括号{},语法如下所示
使用{}创建字典
scores = {'张三': 100, '李四': 98, '王五': 45}
'''
scores = {'张三': 29, '李四': 10, '王五': 40}
print(scores) # {'张三': 29, '李四': 10, '王五': 40}
print(type(scores)) # <class 'dict'>
- 第二种方式,使用内置函数
dict()
。
'''第二种方式,使用内置函数dict()。dict即dictionary(字典)的缩写,语法如下所示。
字典名 = dict(键1=值1, 键2=值2)
'''
dic = dict(name='张三', age=20)
print(dic) # {'name': '张三', 'age': 20}
- 创建空字典
d = {}
print(d) # {}
1.5字典元素的获取
根据键key
获取字典的值value
# 1.使用 [] 获取
scores = {'张三': 29, '李四': 10, '王五': 40}
print('张三' in scores) # True
print('张三' not in scores) # False
print(scores['张三']) # 29
# 2.使用 get()方法
print(scores.get('张三')) # 29
print(scores.get('柽柳')) # None
print(scores.get('麻子', 99)) # 99是在查找 麻子值的(value)不存在时的一个默认值
2、字典类型的操作
2.1字典的操作函数
Python
内置数据结构:字典dict()
类源代码:
class dict(object):
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
"""
def clear(self): # real signature unknown; restored from __doc__
""" D.clear() -> None. Remove all items from D. """
pass
def copy(self): # real signature unknown; restored from __doc__
""" D.copy() -> a shallow copy of D """
pass
@staticmethod # known case
def fromkeys(*args, **kwargs): # real signature unknown
""" Create a new dictionary with keys from iterable and values set to value. """
pass
def get(self, *args, **kwargs): # real signature unknown
""" Return the value for key if key is in the dictionary, else default. """
pass
def items(self): # real signature unknown; restored from __doc__
""" D.items() -> a set-like object providing a view on D's items """
pass
def keys(self): # real signature unknown; restored from __doc__
""" D.keys() -> a set-like object providing a view on D's keys """
pass
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
"""
pass
def popitem(self, *args, **kwargs): # real signature unknown
"""
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order.
Raises KeyError if the dict is empty.
"""
pass
def setdefault(self, *args, **kwargs): # real signature unknown
"""
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
"""
pass
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
def values(self): # real signature unknown; restored from __doc__
""" D.values() -> an object providing a view on D's values """
pass
def __contains__(self, *args, **kwargs): # real signature unknown
""" True if the dictionary has the specified key, else False. """
pass
def __delitem__(self, *args, **kwargs): # real signature unknown
""" Delete self[key]. """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
# (copied from class doc)
"""
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __reversed__(self, *args, **kwargs): # real signature unknown
""" Return a reverse iterator over the dict keys. """
pass
def __setitem__(self, *args, **kwargs): # real signature unknown
""" Set self[key] to value. """
pass
def __sizeof__(self): # real signature unknown; restored from __doc__
""" D.__sizeof__() -> size of D in memory, in bytes """
pass
__hash__ = None
字典类型的一些通用操作函数
操作函数 | 描述 |
---|---|
dict() |
生成一个字典 |
len(d) |
字典d 元素的个数(长度) |
min(d) |
字典d 中键的最最小值 |
max(d) |
字典d 中键的最最大值 |
2.2字典的操作方法
字典类型有一些操作方法,使用的语法格式为:<字典对象名>.<方法名>(<方法参数>)
操作方法 | 描述 |
---|---|
d.keys() |
返回字典d 所有键的信息 |
d.values() |
返回字典d 所有值的信息 |
d.items() |
返回字典d 所有键值对 |
d.get(key, default) |
键存在则返回相应值,否则返回默认值default |
d.pop(key, default) |
键存在则返回相应值,同时删除键值对,否则返回默认值default |
d.popitem() |
随机从字典中取出一个兼职对,以元组(key, value) 的形式返回,同时将该键值对从字典中删除。 |
d.clear() |
删除所有的键值对,清空字典 |
2.3字典元素的增删改操作
scores = {'张三': 29, '李四': 10, '王五': 40}
- key的判断
# key的判断
scores = {'张三': 29, '李四': 10, '王五': 40}
print('张三' in scores) # True
print('张三' not in scores) # True
- 字典的删除
# 字典元素的删除
del scores['张三'] # 删除指定的键值对
print(scores) # {'李四': 10, '王五': 40}
- 字典的清除
# 清空字典 clear()方法
scores.clear()
print(scores) # {}
- 字典元素的新增
# 新增元素
scores['陈六'] = 20
print(scores) # {'陈六': 20}
- 字典元素值的修改
# 修改value
scores['陈六'] = 100
print(scores) # {'陈六': 100}
2.4字典视图的获取
- 获取所有的键,
<字典对象名>.keys()
方法 返回值为列表
# 获取所有的键 .keys()方法 返回值为列表
scores = {'张三': 29, '李四': 10, '王五': 40}
print(scores.keys()) # dict_keys(['张三', '李四', '王五'])
print(type(scores.keys())) # <class 'dict_keys'>
print(list(scores.keys())) # ['张三', '李四', '王五']
- 获取所有的值,
<字典对象名>.value()
方法,返回值为列表
# 获取所有的值 <字典对象名>.value()方法 返回值为列表
dict_values = scores.values()
print(dict_values) # dict_values([29, 10, 40])
print(type(dict_values)) # <class 'dict_values'>
print(list(dict_values)) # [29, 10, 40]
- 获取所有的键值对,
<字典对象名>.items()
方法 返回值为元组
# 获取所有的键值对 返回值为元组
print(scores.items())
# dict_items([('张三', 29), ('李四', 10), ('王五', 40)])
2.5字典元素的遍历
字典元素的遍历:使用for-in
循环
# 字典元素的遍历
scores = {'张三': 29, '李四': 10, '王五': 40}
for item in scores:
print(item, scores[item])
3、字典的特点
1.键key
不可以重复,值value
可以重复2.字典中元素是无序的
3.字典会浪费大的内存,是一种使用空间换时间的数据结构,但是查询速度快。
4、字典生成式
- 内置函数
zip()
用于将可迭代对象作为参数,将对象中对应的元素打包成一个元组,然后返回由这些元组组成的列表
- 字典生成式:
{key: value for key, value in zip(items,prices)}
items = ['Fruits', 'Books', 'Others'] # 键的列表
prices = [96, 78, 85] # 值的列表
d = {items: prices for items, prices in zip(items, prices)} # 两个列表生成一个字典
print(d) # {'Fruits': 96, 'Books': 78, 'Others': 85}
# .upper()方法 键字母变大写
d = {items.upper(): prices for items, prices in zip(items, prices)} # 两个列表生成一个字典
print(d) # {'Fruits': 96, 'Books': 78, 'Others': 85}
items = ['Fruits', 'Books', 'Others'] # 键的列表
prices = [96, 78, 85] # 值的列表
a = dict(zip(items, prices))
print(a) # {'Fruits': 96, 'Books': 78, 'Others': 85}