pythondict函数的作用_python dict函数-焦点快播

2023-04-30 09:46:00    来源:互联网


(资料图片仅供参考)

1、#字典的添加、删除、修改操作dict={"a":"apple","b":"banana","g":"grape","o":"orange"}dict["w"]="watermelon"del(dict["a"])dict["g"]="grapefruit"printdict.pop("b")printdictdict.clear()printdict#字典的遍历dict={"a":"apple","b":"banana","g":"grape","o":"orange"}forkindict:print"dict[%s]="%k,dict[k]#字典items()的使用dict={"a":"apple","b":"banana","c":"grape","d":"orange"}#每个元素是一个key和value组成的元组。

2、以列表的方式输出printdict.items()#调用items()实现字典的遍历dict={"a":"apple","b":"banana","g":"grape","o":"orange"}for(k,v)indict.items():print"dict[%s]="%k,v#调用iteritems()实现字典的遍历dict={"a":"apple","b":"banana","c":"grape","d":"orange"}printdict.iteritems()fork,vindict.iteritems():print"dict[%s]="%k,vfor(k,v)inzip(dict.iterkeys(),dict.itervalues()):print"dict[%s]="%k,v#使用列表、字典作为字典的值dict={"a":("apple",),"bo":{"b":"banana","o":"orange"},"g":["grape","grapefruit"]}printdict["a"]printdict["a"][0]printdict["bo"]printdict["bo"]["o"]printdict["g"]printdict["g"][1]dict={"a":"apple","b":"banana","c":"grape","d":"orange"}#输出key的列表printdict.keys()#输出value的列表printdict.values()#每个元素是一个key和value组成的元组。

3、以列表的方式输出printdict.items()dict={"a":"apple","b":"banana","c":"grape","d":"orange"}it=dict.iteritems()printit#字典中元素的获取方法dict={"a":"apple","b":"banana","c":"grape","d":"orange"}printdictprintdict.get("c","apple")printdict.get("e","apple")#get()的等价语句D={"key1":"value1","key2":"value2"}if"key1"inD:printD["key1"]else:print"None"#字典的更新dict={"a":"apple","b":"banana"}printdictdict2={"c":"grape","d":"orange"}dict.update(dict2)printdict#udpate()的等价语句D={"key1":"value1","key2":"value2"}E={"key3":"value3","key4":"value4"}forkinE:D[k]=E[k]printD#字典E中含有字典D中的keyD={"key1":"value1","key2":"value2"}E={"key2":"value3","key4":"value4"}forkinE:D[k]=E[k]printD#设置默认值dict={}dict.setdefault("a")printdictdict["a"]="apple"dict.setdefault("a","default")printdict#调用sorted()排序dict={"a":"apple","b":"grape","c":"orange","d":"banana"}printdict#按照key排序printsorted(dict.items(),key=lambdad:d[0])#按照value排序printsorted(dict.items(),key=lambdad:d[1])#字典的浅拷贝dict={"a":"apple","b":"grape"}dict2={"c":"orange","d":"banana"}dict2=dict.copy()printdict2#字典的深拷贝importcopydict={"a":"apple","b":{"g":"grape","o":"orange"}}dict2=copy.deepcopy(dict)dict3=copy.copy(dict)dict2["b"]["g"]="orange"printdictdict3["b"]["g"]="orange"printdict。

本文到此分享完毕,希望对大家有所帮助。

关键词: