‘‘‘Dict 字典存储的是key-value键值对形式的值特点: 1.无序,因为无下标 2.key值是唯一的,自动去重‘‘‘ person = { "name":"xiaoming", "age" : 20} #根据key查询值print(person["name"])print(person["age"])print(person.get("name","没有"))#没有key就返回默认值 #查询是否包含某个keyprint("age" in person)#person.haskey("name") python 2.xx #删除key并对应的值#del person["name"]print(person) #删除并返回被删除的key-value#print(person.pop("name",0))#print(person) #打印所有的keyprint(person.keys()) #合并连个字典a={1:2,"a":"b",3:4}b={1:"1","c":"d",5:6}a.update(b)print(a) #items 字典转换成元组print(a.items()) #fromkeys 初始化一个列表并赋予默认的值#注意这里相当于浅拷贝print(person.fromkeys(["name","age"],"test")) #循环字典 推荐for p in person: print(p,person[p]) #不要用这种,需要字典先转换成列表,效率低下for k,v in person.items(): print(k,v)
时间: 2024-10-29 16:52:40