Python 之 字典及基本操作
字典(dictionary)是Python里面一种无序存储结构,存储的是键值对 key - value,字典是一种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型。
字典的创建形式如:d = {key1 : value2, key2 : value2}。
说明: 字典以 "{" 来标识,键与值之间用 ":" 来关联,不同项之间用 "," 来分隔。
字典的创建:
dict_empty = {} # 创建空字典
dict_empty2 = dict() # 用工厂函数创建空字典
dic_protocol = {'ftp':21, 'smtp':25, 'http':80, 'https':443} # 创建有数据的字典
dic_mix = {'Alice': 18, 1:38, 2:39}
article = {'Name':'Python之字典', 'Date':'2017-4-10', 'label':['python','dict', 'file']}
字典的访问:
print(article) # 输出: {'Date': '2017-4-10', 'Name': 'Python之字典', 'label': ['python', 'dict', 'file']}
print(article['Name']) # 输出: Python之字典
print(article['Date']) # 输出: 2017-4-10
print(article['label']) # 输出: ['python', 'dict', 'file']
print(dic_mix['Alice']) # 输出: 18
print(dic_mix[1]) # 输出: 38
字典的增加、删除、修改:
增加:
article['Author'] = '张三' # 在article中增加一项,增加后结果为:{'Date': '2017-4-10', 'Name': 'Python之字典', 'label': ['python', 'dict', 'file'], 'Author': '张三'}
修改:
article['Author'] = '张好古' # 修改元素值,输出:{'Date': '2017-4-10', 'Name': 'Python之字典', 'label': ['python', 'dict', 'file'], 'Author': '张好古'}
删除:
del(article['Author']) # 删除Author,输出: {'Date': '2017-4-10', 'Name': 'Python之字典', 'label': ['python', 'dict', 'file']}
article.clear() # 清除所有记录
字典的遍历:
for k in article:
print(k, end=' ')
print(article[k])
# 输出:
Date 2017-4-10
Name Python之字典
label ['python', 'dict', 'file']
浙公网安备 33010602011771号