python dict函数(python dict函数)
作者:访客发布时间:2023-10-06分类:沙雕文案浏览:91评论:0
您好,现在程程来为大家解答以上的问题。python dict函数,python dict函数相信很多小伙伴还不知道,现在让我们一起来看看吧!
1、#字典的添加、删除、修改操作dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}dict["w"] = "watermelon"del(dict["a"])dict["g"] = "grapefruit"print dict.pop("b")print dictdict.clear()print dict#字典的遍历dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}for k in dict: print "dict[%s] =" % k,dict[k]#字典items()的使用dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}#每个元素是一个key和value组成的元组。
2、以列表的方式输出print dict.items()#调用items()实现字典的遍历dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}for (k, v) in dict.items(): print "dict[%s] =" % k, v#调用iteritems()实现字典的遍历dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}print dict.iteritems()for k, v in dict.iteritems(): print "dict[%s] =" % k, vfor (k, v) in zip(dict.iterkeys(), dict.itervalues()): print "dict[%s] =" % k, v #使用列表、字典作为字典的值dict = {"a" : ("apple",), "bo" : {"b" : "banana", "o" : "orange"}, "g" : ["grape","grapefruit"]}print dict["a"]print dict["a"][0]print dict["bo"]print dict["bo"]["o"]print dict["g"]print dict["g"][1] dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}#输出key的列表print dict.keys()#输出value的列表print dict.values()#每个元素是一个key和value组成的元组。
3、以列表的方式输出print dict.items()dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}it = dict.iteritems()print it#字典中元素的获取方法dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}print dictprint dict.get("c", "apple") print dict.get("e", "apple")#get()的等价语句D = {"key1" : "value1", "key2" : "value2"}if "key1" in D: print D["key1"]else: print "None"#字典的更新dict = {"a" : "apple", "b" : "banana"}print dictdict2 = {"c" : "grape", "d" : "orange"}dict.update(dict2)print dict#udpate()的等价语句D = {"key1" : "value1", "key2" : "value2"}E = {"key3" : "value3", "key4" : "value4"}for k in E: D[k] = E[k]print D#字典E中含有字典D中的keyD = {"key1" : "value1", "key2" : "value2"}E = {"key2" : "value3", "key4" : "value4"}for k in E: D[k] = E[k]print D#设置默认值dict = {}dict.setdefault("a")print dictdict["a"] = "apple"dict.setdefault("a","default")print dict#调用sorted()排序dict = {"a" : "apple", "b" : "grape", "c" : "orange", "d" : "banana"}print dict #按照key排序 print sorted(dict.items(), key=lambda d: d[0])#按照value排序 print sorted(dict.items(), key=lambda d: d[1])#字典的浅拷贝dict = {"a" : "apple", "b" : "grape"}dict2 = {"c" : "orange", "d" : "banana"}dict2 = dict.copy()print dict2#字典的深拷贝import copydict = {"a" : "apple", "b" : {"g" : "grape","o" : "orange"}}dict2 = copy.deepcopy(dict)dict3 = copy.copy(dict)dict2["b"]["g"] = "orange"print dictdict3["b"]["g"] = "orange"print dict。
本文就为大家分享到这里,希望小伙伴们会喜欢。
- 沙雕文案排行
- 最近发表
- 标签列表
-