字典dic = {key:value}
# @Author : Stuff
info = {
"name":{"first name":"tang","last name":"sanzang"},
"year":10000,
"addr":["chang an","nv er guo"]
}
print(info["name"])
info["year"]=20000#修改value
info["sex"]= "man"#增加一个键值
print(info)
{'first name': 'tang', 'last name': 'sanzang'}
{'name': {'first name': 'tang', 'last name': 'sanzang'}, 'year': 20000, 'addr': ['chang an', 'nv er guo'], 'sex': 'man'}
生成字典的方法
1.通过列表生成字典
# @Author : Stuff
name =["zhao","qian","sun","li"]
age =[1,2,3,4,5]
info =dict(zip(name,age))
print(info)
{'zhao': 1, 'qian': 2, 'sun': 3, 'li': 4}
2.通过数组组成的列表生成字典
# @Author : Stuff
d = dict([("aaa",111),("bbb",222),("ccc",333)])
print(d)
{'aaa': 111, 'bbb': 222, 'ccc': 333}
3.字典的合并
# @Author : Stuff
a={"aa":11,
"bb":22,
"cc":33}
b ={
"dd":44,
"ee":55
}
a.update(b)
print(a)
{'aa': 11, 'bb': 22, 'cc': 33, 'dd': 44, 'ee': 55}
4.怎样查看不存在的键值
由于直接查询不存在的值会报错
KeyError: 'd'
有两种方式
- 通过in方法判断
# @Author : Stuff
a={"aa":11,"bb":22,"cc":33}
print("d"in a)
if not "d" in a:
print("miss")
False
miss
- 使用get命令
# @Author : Stuff
a={"aa":11,"bb":22,"cc":33}
print(a.get("d",0))#get的第二个值表示key的值不存在时返回的值,默认是None
0
5.一次性获得全部的key或value
# @Author : Stuff
a={"aa":11,"bb":22,"cc":33,"dd":44,"ee":55}
print(list(a.keys()))#a.keys返回的是迭代器,而不是列表,
print(list(a.values()))
print(list(a.items()))
['aa', 'bb', 'cc', 'dd', 'ee']
[11, 22, 33, 44, 55]
[('aa', 11), ('bb', 22), ('cc', 33), ('dd', 44), ('ee', 55)]
6.字典的删除
del和pop
# @Author : Stuff
a={"aa":11,"bb":22,"cc":33,"dd":44,"ee":55}
del a["aa"]
print(a)
print(a.pop("bb"))
print(a)
{'bb': 22, 'cc': 33, 'dd': 44, 'ee': 55}
22
{'cc': 33, 'dd': 44, 'ee': 55}