Python字典
一、 创建字典
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 。而且字典内的键值对是无序的。并不是你创建时什么样子print时就是什么样子,键值对的顺序可能会变。
键必须是唯一的,但值则不必。值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
1.直接创建
a={‘name’:‘tom’,age’:12,’hobby’:[‘sing’,swimming],’number_of_family’:{‘father’:‘dad’,‘mother’:‘mom’}}
2.利用类创建
1)利用元组创建
b=dict((('name','tom'),('age',12))) #利用元组创建
print(b) #{'name': 'tom', 'age': 12}
2)利用列表创建
c=dict([['name','tom'],['age',12]]) #利用列表创建
print(c) #{'name': 'tom', 'age': 12}
二、 字典的操作
1.增
1)直接增加
c={'name': 'tom', 'age': 12} #创建字典c
c[‘mother’]=’mom’ #增加[‘mother’: ’mom’]键值对
print(c) #{'mother': 'mom', 'age':12, 'name': 'tom'}
2)使用setdefault
Setdefault是又返回值的创建,可以返回增加键值对的键的值。创建的同时会检索原字典里是否已有该键值对,如果有则不再创建但可以返回键的值,如果没有则创建。且每次只能增加一个键值对,不能同时增加多个。
d={'age': 12, 'name': 'tom'} #创建字典d
ret=d.setdefault('mother','mom') #增加{'mother':'mom'}
print(d) #{'name': 'tom', 'mother':'mom', 'age': 12}
print(ret) # mom
2.查
1)直接查询
d={'age': 12, 'name': 'tom'} #创建字典d
print (d[‘name’]) # tom
2)查询字典里所有的键名
d={'age': 12, 'name': 'tom'} #创建字典d
print (list(d.keys())) #通过用类创建列表的方法列出键名[ 'age', 'name']
3)以列表嵌套元组的方式显示字典内容
d={'age': 12, 'name': 'tom'} #创建字典d
print(list(d.items())) &nb