python数据结构 - 字典

字典的定义

定义:是一个内置的数据结构,允许将数据与键而不是数字关联,这样可以使内存中的数据与实际数据的结构保持一致。
别名:映射、散列、关联数组
特性:

  • 可以动态扩展存储额外的键值对
  • 会维护关联关系
  • 不会维持插入的顺序

字典的相关操作

创建字典

>>> dictionary_1={}
>>> dictionary_2 =dict()
>>> type(dictionary_1)
<class 'dict'>
>>> type(dictionary_2)
<class 'dict'>

增加数据

>>> dictionary_1['name'] = 'John'
>>> dictionary_1['birthday'] = '2012-10-22'
>>> dictionary_1['name']
'John'

>>> dictionary_2 = {'name' : 'Merry','birthday': '2012-10-22','hobby':['swim','play','read']}
>>> dictionary_2['name']
'Merry'
>>> dictionary_2['hobby']
['swim', 'play', 'read']
>>> dictionary_2['hobby'][0]
'swim'

>>> dictionary_1['number'] = '123'
>>> dictionary_2['number'] = [123,2,3]
>>> dictionary_1
{'name': 'John', 'birthday': '2012-10-22', 'number': '123'}
>>> dictionary_2
{'name': 'Merry', 'birthday': '2012-10-22', 'hobby': ['swim', 'play', 'read'], 'number': [123, 2, 3]}

猜你喜欢

转载自blog.csdn.net/Sonia_du/article/details/88418269