目录
1. 字典的关键特征
字典是 Python 中唯一实现映射关系的内置类型。
字典的关键符号是大括号({})和冒号(:);
除空字典外,只由{}组成的是集合。
#除空字典外没有冒号(:)形成映射关系的,是集合
d = {'a','b','c'}
type(d)
<class 'set'>
#空字典没有冒号(:)
d = {}
type(d)
<class 'dict'>
#同时有{}和:的类型都是字典
d = {'a':0,'b':1,'c':2}
type(d)
<class 'dict'>
2. 字典取值
我们将冒号的左边称为字典的 “键”,右边称为字典的 “值”。
在字典中,只要我们提供键,就可以获取其对应的值。方法跟序列类似,只不过这次在方括号中,咱们使用的是键,而非索引值。
通过d[key]直接获取字典某个键对应的值:
d = {'a':1,"b":2,"c":3}
d['a']
1
字典不支持索引或者切片取值:
d[0]
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 0
d[:]
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'slice'
3. 字典:键
字典所有的键都不相同,如果创建或新增同名键,则之后修改同名键对应的值;
注意,键所赋的整数、浮点数、复数数值相同,则视为相同的键;
字典键需要为可哈希对象,参见可哈希:hashable ,常见可哈希对象包括字符串、元组、整数、浮点数、复数等,不支持列表、字典,以及带有列表、字典元素的元组或集合。
#字典所有的键都不相同,如果创建或新增同名键,则之后修改同名键对应的值
#键所赋的整数、浮点数、复数数值相同,则视为相同的键;
d = {1:'a',1.00:'b',1+0j:'c'}
d
{1: 'c'}
d = d.fromkeys('aba',1)
d
{'a': 1, 'b': 1}
d = {1:'a',2:'b',3:'c'}
d[1.0] = 'x'
d
{1: 'x', 2: 'b', 3: 'c'}
#字典键支持字符串、元组、整数、浮点数、复数
d = {0:'a',1.1:'b',-2j:'c','3AA':'d',(4,5,6):'e'}
d
{0: 'a', 1.1: 'b', (-0-2j): 'c', '3AA': 'd', (4, 5, 6): 'e'}
#字典键不支持字符串,以及带有字符串元素的元组
d = {[1]:1}
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'list'
d = {([4],5,6):1}
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'list'
4. 字典:值
字典值支持字典、字符串、列表、元组、整数、浮点数、复数;
可以通过d[key] 修改或使用字典键对应的值。
#字典值支持字典、字符串、列表、元组、整数、浮点数、复数
d= {'a':{'a':1},'b':'a1@','c':[[1],(2,),3],'d':('1',['2',3],(4,5,6)),'e':1,'f':2.0,'g':-3j}
d
{'a': {'a': 1}, 'b': 'a1@', 'c': [[1], (2,), 3], 'd': ('1', ['2', 3], (4, 5, 6)), 'e': 1, 'f': 2.0, 'g': (-0-3j)}
#可以通过d[key] 修改或使用字典键对应的值
d['a']['a']
1
d['b'].islower()
True
d['c'].append('456')
d
{'a': {'a': 1}, 'b': 'a1@', 'c': [[1], (2,), 3, '456'], 'd': ('1', ['2', 3], (4, 5, 6)), 'e': 1, 'f': 2.0, 'g': (-0-3j)}
d['e'] +3
4
5. 创建字典
创建字典有很多种方法,官方文档列举了6种方法,实操如下:
5.1 直接创建字典
直接使用大括号{}、冒号:,将映射关系给“套牢”。
d = {'a':1,"b":2,"c":3}
d
{'a': 1, 'b': 2, 'c': 3}
5.2 dict()键值对参数创建
第二种方法,使用 dict() 函数,跟 list()、tuple()、str() 类似,dict() 函数用来生成字典,原型:
class dict(**kwarg)
每个参数就是一个键值对,键与值直接使用等号挂钩,等号左边是键、右边是值;
使用dict()生成字典,不能往键上面加引号,即使是键是一个字符串,否则报错;
使用dict()生成字典,“键” 必须是合法的 Python 标识符,参见2.变量名要求: ,否则报错。
#每个参数就是一个键值对,键与值直接使用等号挂钩,等号左边是键、右边是值;
d = dict(a=1,b=2,c=3)
d
{'a': 1, 'b': 2, 'c': 3}
#使用dict()生成字典,字符串不能加双引号,否则报错
d = dict('a'=1,'b'=2)
File "<input>", line 1
d = dict('a'=1,'b'=2)
^
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
#使用dict()生成字典,键必须符合变量名要求,否则报错
dict(a_1中文='a')
{'a_1中文': 'a'}
dict(1a='a')
File "<input>", line 1
dict(1a='a')
^
SyntaxError: invalid syntax
dict(a$='a')
File "<input>", line 1
dict(a$='a')
^
SyntaxError: invalid syntax
5.3 dict()列表参数创建
第三种,dict()函数使用列表作为参数,原型:
class dict(iterable)
列表中的每个元素是使用元组包裹起来的键值对。
d = dict([('a',1),('b',2),('c',3)])
d
{'a': 1, 'b': 2, 'c': 3}
5.4 dict()字典参数创建
第四种是将第一种方法作为参数给到 dict() 函数,原型:
class dict(mapping)
即直接将字典作为dict()的参数。
d = dict({'a':1,"b":2,"c":3})
d
{'a': 1, 'b': 2, 'c': 3}
5.5 dict()混合参数创建
第五种,混合使用方法2~4,原型:
class dict(mapping, **kwargs)
class dict(iterable, **kwargs)
混合使用时,只能添加一个列表或字典作为dict()函数参数,否则报错;
混合使用时,列表或字典需置于dict()函数的参数第一位,否则报错;
添加一个列表或字典作为dict()函数的第一位参数后,随后可以参照方法2,再添加多个键值对作为参数。
#混合使用列表和键值对
d = dict([('a',1),('b',2)],c=3)
d
{'a': 1, 'b': 2, 'c': 3}
#混合使用字典和多个键值对
d = dict({'a':0,'b':1},c=2,d=3,e=4)
d
{'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
#列表和字典不是dict()函数的第一位参数,报错
d = dict(c=2,{'a':0,'b':1})
File "<input>", line 1
d = dict(c=2,{'a':0,'b':1})
^
SyntaxError: positional argument follows keyword argument
d = dict(c=3,[('a',1),('b',2)])
File "<input>", line 1
d = dict(c=3,[('a',1),('b',2)])
^
SyntaxError: positional argument follows keyword argument
#使用多个列表和字典,报错
d = dict([('a',1),('b',2)],[('c',3),('d',4)])
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: dict expected at most 1 argument, got 2
d = dict([('a',1),('b',2)],{'c':3,'d':4})
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: dict expected at most 1 argument, got 2
5.6 dict()使用zip()生成参数创建
zip() 函数的作用是创建一个聚合多个可迭代对象的迭代器,原型:
class dict(iterable, **kwargs)
生成的迭代器也可以作为参数传给 dict() 函数。
d = dict(zip(['a','b','c','d'],[1,2,3,4]))
d
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
d = dict(zip('abcd',(1,2,3,4)))
d
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
d = dict(zip(['a','b','c','d'],[1,2,3,4]),f=5)
d
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'f': 5}

本文介绍了Python字典的基础知识,包括字典的关键特征、取值方式、键和值的特点,以及多种创建字典的方法,如直接创建、dict()函数创建、使用列表和zip()函数创建等。
1062





