Python 字典

<center> Python序列 </center>


本文章总结了董付国老师的Pthon程序设计(第2版)书的内容,仅供个人学习使用,如有侵权,立刻删除 by:mfdy


文章链接:mfdy’s blog: Python 序列


CSDN目录:https://blog.csdn.net/mofadiyu/article/details/90178542

2.3 字典

字典是“键-值对”的无序可变序列,字典中的每个元素包含两个部分:“键”和“值”。
定义字典时,每个元素的键和值用冒号分隔,元素之间用逗号分隔,所有的元素放在一对大括号“{}”中。
字典中的键可以为任意不可变数据,比如整数、实数、复数、字符串、元组等等。

2.3.1 字典创建与删除

  1. 使用=将一个字典赋值给一个变量即可创建一个字典变量
a_dict = {'asd':'qwe', 'zxc':'2'}
>>> a_dict
{'asd': 'qwe', 'zxc': '2'}
  1. 使用内置函数dict()通过已有数据快速创建字典
keys = ['a', 'b', 'c', 'd']
values = [1, 2, 3, 4]
dictionary = dict(zip(keys, values))
>>> dictionary
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

同时,也可创建空字典

x = dict()
>>> x
{}
  1. 使用内置函数dict()根据给定的“键-值对”来创建字典
d = dict(name='Dong', age=37)
>>> d
{'name': 'Dong', 'age': 37}
  1. 以给定内容为“键”,创建“值”为空的字典
adict = dict.fromkeys(['name', 'age', 'sex'])
>>> adict
{'name': None, 'age': None, 'sex': None}

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

adict = dict.fromkeys('age', 5)
>>> adict
{'a': 5, 'g': 5, 'e': 5}

adict = dict.fromkeys(['age'], 5)
>>> adict
{'age': 5}
  1. 可以使用del删除整个字典或者字典中指定的元素,具体参考2.3.3

2.3.2 字典元素的读取

  1. 以键作为下标可以读取字典元素,若键不存在则抛出异常
aDict = {'name':'Dong', 'sex':'male', 'age':37}
>>> aDict['name']
Dong
>>> aDict['tel']
Traceback (most recent call last):
  File "1.py", line 3, in <module>
    print(aDict['tel'])
KeyError: 'tel'
  1. 使用字典对象的get方法获取指定键对应的值,并且可以在键不存在的时候返回指定值

get()方法语法:

dict.get(key, default = None)

其中:
key – 字典中要查找的键。
default – 如果指定键的值不存在时,返回该默认值值。
get()函数返回指定键的值,如果值不在字典中返回默认值None。

>>> print(aDict.get('address'))
None
>>> print(aDict.get('address', 'SDIBT'))
SDIBT

aDict['score'] = aDict.get('score',[])
aDict['score'].append(98)
aDict['score'].append(97)
>>> aDict
{'score': [98, 97]}
  1. 使用字典对象的items()方法可以返回字典的键、值对列表
    使用字典对象的keys()方法可以返回字典的键列表
    使用字典对象的values()方法可以返回字典的值列表
aDict = {'name':'Dong', 'sex':'male', 'age':37}
for item in aDict.items():
  print(item)

for key in aDict.keys(): 
  print(key)

for value in aDict.values():
  print(value)

for key, value in aDict.items():
  print(key, value)

输出结果为:

('name', 'Dong')
('sex', 'male')
('age', 37)
name
sex
age
Dong
male
37
name Dong
sex male
age 37

2.3.3 字典元素的添加与修改

  1. 当以指定键为下标为字典赋值时,若键存在,则可以修改该键的值;若不存在,则表示添加一个键、值对。
# 修改元素值
>>> aDict['age'] = 38
>>> aDict
{'age': 38, 'name': 'Dong', 'sex': 'male'}

# 增加新元素
>>> aDict['address'] = 'SDIBT'
>>> aDict
{'age': 38, 'address': 'SDIBT', 'name': 'Dong', 'sex': 'male'}
  1. 使用字典对象的update方法修改键值,当键不存在的时候则自动添加进去
aDict = {'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}
aDict.update({'a':'a','b':'b'})
>>> (aDict)
{'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male', 'a': 'a', 'b': 'b'}

aDict.update({'a':'dss','b':'afd'})
>>> print(aDict)
{'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male', 'a': 'dss', 'b': 'afd'}
  1. 删除
     使用del删除字典中指定键的元素
     使用字典对象的clear()方法来删除字典中所有元素
     使用字典对象的pop()方法删除并返回指定键的元素
     使用字典对象的popitem()方法删除并返回字典中的一个元素

2.3.4 有序字典

import collections
x = collections.OrderedDict()
x['b'] = 5
x['a'] = 3
x['c'] = 8
>>> x
OrderedDict([('b', 5), ('a', 3), ('c', 8)])
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务