字典:Python中字典是一种key-value的数据类型,就像新华字典那样,可以根据笔划,字母来查找对应的内容。
dict = {
'num1101':"Alice",
'num1102':"Alen",
'num1103':"Alex",
'num1104':"BOb",
'num1105':"Linda",
}
dict = {
'num1101':"Alice",
'num1102':"Alen",
'num1103':"Alex",
'num1104':"BOb",
'num1105':"Linda",
}
print(dict)
dict["num1106"] = "June这里是新元素"
print(dict)
dict.pop("num1101") #标准删除方法
del dict["num1102"] #删除指定元素
dict.popitem() #删除最后一个元素
print(dict)
dict['num1101'] = "爱丽丝"
dict = {
'num1101':"Alice",
'num1102':"Alen",
'num1103':"Alex",
'num1104':"BOb",
'num1105':"Linda",
}
print("num1103" in dict) #返回检索的元素是否存在,Trur,false
print(dict.get("num1105")) #返回对应的值
print(dict["num1104"]) #如检索值不存在会报错
print(dict["num1109"])
#输出如下:
True
Traceback (most recent call last):
Linda
File "/home/cc/mycode/day3/dict.py", line 11, in
BOb
print(dict["num1109"])
KeyError: 'num1109'
Process finished with exit code 1
多级字典嵌套即在字典中定义字典;
book = {
"学习工具":{
"1001":["百科全书"],
"1002": ["英汉互译"],
"1003": ["Python入门"],
},
"小说":{
"1101":["解忧杂货店"],
"1102": ["好吗好的"],
"1103": ["百年孤独"],
},
"名著":{
"1201":["西游记","红楼梦"],
}
}
book["学习工具"]["1003"][0] += ",学习Python的好帮手"
print(book["学习工具"]["1003"])
dict = {
'num1101':"Alice",
'num1102':"Alen",
'num1103':"Alex",
'num1104':"BOb",
'num1105':"Linda",
}
print(dict.values())
输出:dict_values(['Alice', 'Alen', 'Alex', 'BOb', 'Linda'])
dict = {
'num1101':"Alice",
'num1102':"Alen",
'num1103':"Alex",
'num1104':"BOb",
'num1105':"Linda",
}
print(dict.keys())
输出:dict_keys(['num1101', 'num1102', 'num1103', 'num1104', 'num1105'])
dict = {
'num1101':"Alice",
'num1102':"Alen",
'num1103':"Alex",
'num1104':"BOb",
'num1105':"Linda",
}
dict.setdefault("num1106","Jane") #检索后不存在该元素,添加进字典
dict.setdefault("num1101","爱丽丝") #检索后存在该元素,字典内容不变
print(dict)
输出应为:{‘num1101’: ‘Alice’, ‘num1102’: ‘Alen’, ‘num1103’: ‘Alex’, ‘num1104’: ‘BOb’, ‘num1105’: ‘Linda’, ‘num1106’: ‘Jane’}
dict = {
'num1101':"Alice",
'num1102':"Alen",
'num1103':"Alex",
'num1104':"BOb",
'num1105':"Linda",
}
name = {
1:2,"num1105":"Linda",3:4
}
dict.update(name)
print(dict)
{'num1101': 'Alice', 'num1102': 'Alen', 'num1103': 'Alex', 'num1104': 'BOb', 'num1105': 'Linda', 1: 2, 3: 4}