本文主要是介绍柚子的Python学习笔记之字典,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
字典:Python中字典是一种key-value的数据类型,就像新华字典那样,可以根据笔划,字母来查找对应的内容。
定义语法:
dict = {'num1101':"Alice",'num1102':"Alen",'num1103':"Alex",'num1104':"BOb",'num1105':"Linda",
}
字典的特性:
- 无序
- key必须唯一,所以字典天生去重,不存在重复元素
字典操作
增加
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):
LindaFile "/home/cc/mycode/day3/dict.py", line 11, in <module>
BObprint(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"])
其他操作
values
dict = {'num1101':"Alice",'num1102':"Alen",'num1103':"Alex",'num1104':"BOb",'num1105':"Linda",
}print(dict.values())
输出:dict_values(['Alice', 'Alen', 'Alex', 'BOb', 'Linda'])
keys
dict = {'num1101':"Alice",'num1102':"Alen",'num1103':"Alex",'num1104':"BOb",'num1105':"Linda",
}
print(dict.keys())输出:dict_keys(['num1101', 'num1102', 'num1103', 'num1104', 'num1105'])
setdefault
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’}
update
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}
items
循环
这篇关于柚子的Python学习笔记之字典的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!