1、定义字典:
dicts = {“name”:”Mike”,”sex”:”male”}
print dicts[“name”]
print dicts[“sex”]
2、添加键值
dicts = {“name”:”Mike”,”sex”:”male”}
dict[“age”] = 20
print dicts
答:dicts = {“name”:”Mike”,”sex”:”male”,”age”:20}
3、修改键值
dicts[“name”] = “Jhon”
4、删除键值
del dicts[“name”] = “Jhon”
5、遍历字典
(1)、遍历键值
for i in dicts.items():
Print i
(2)、遍历键
for i in dicts.keys():
Print i
(3)、遍历值
for i in dicts.values():
Print i
6、判断元素是否在字典中(in 和not in )
7、字典列表
a = {"color":"green","points":5}
b = {"color":"yellow","points":10}
c = {"color":"red","points":15}
total =[a,b,b]
for alien in total:
print alien
8、字典中存列表
print '\n第5题\n'
dicts5 = {
"name":["jack","mary"],
"sex":["male","female"]
}
for i ,j in dicts5.items():
for k in j:
print i.title() +":"+ k.title()+"\n"
9、字典中存储字典
dicts6 ={
"Mike":{
"first":"robot",
"last":"steven",
"location":"lonodo"
},
"Mary":{
"first":"ss",
"last":"dd",
"location":"paris"
}
}
for username,userinfo in dicts6.items():
print username
for i,j in userinfo.items():
print i,j