vue项目接口域名动态的获取方法
349
2022-08-31
python dict字典详解(python怎么读)
文章目录
1.字典特点2.字典内置函数3.字典内置方法4.方法运用
增删改查创
4设置默认值5.字典排序6.字典拷贝
浅拷贝深拷贝
7.字典遍历
遍历key遍历值遍历keys和values
8.函数字典传参9.字典推导式
1.字典特点
字典是另一种可变容器模型,且可存储任意类型对象。 字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号 例如:d = {key1 : value1, key2 value2 } 键必须是唯一的,但值则不必 不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住
2.字典内置函数
1 cmp(dict1, dict2)比较两个字典元素。2 len(dict)计算字典元素个数,即键的总数。3 str(dict)输出字典可打印的字符串表示。4 type(variable)返回输入的变量类型,如果变量是字典就返回字典类型。
3.字典内置方法
1 dict.clear() 删除字典内所有元素2 dict.copy() 返回一个字典的浅复制3 dict.fromkeys(seq[, val]) 创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值4 dict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值5 dict.has_key(key) 如果键在字典dict里返回true,否则返回false6 dict.items() 以列表返回可遍历的(键, 值) 元组数组7 dict.keys() 以列表返回一个字典所有的键8 dict.setdefault(key, default=None)和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default9 dict.update(dict2) 把字典dict2的键/值对更新到dict里10 dict.values() 以列表返回字典中的所有值11 pop(key[,default]) 删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。12 popitem() 随机返回并删除字典中的一对键和值。
4.方法运用
增
$ cat dict1.py#!/usr/bin/python#!---coding:utf-8----dic1={'age': 18, 'name': 'alex', 'hobby': 'girl'}dic2={'1':'111','2':'222'}dic2={'1':'111','name':'222'}dic1.update(dic2)print(dic1)print(dic2)for k in dic2: #等同update() dic1[k] = dic2[k]print dic1[root@localhost dict]$ python dict1.py {'1': '111', 'hobby': 'girl', 'age': 18, 'name': '222'}{'1': '111', 'name': '222'}{'1': '111', 'hobby': 'girl', 'age': 18, 'name': '222'}
第二种
dic2={'1':'111','2':'222'}dic2['xx']='cccc'print dic2
$ python dict15.py {'1': '111', 'xx': 'cccc', '2': '222'}
删
delpop(‘key’)popitem()clear()
cat dict3.py#!/usr/bin/python# -*- coding: UTF-8 -*-dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First', 'weight': 56, 'gender': 'man'};del dict['Name']; # 删除键是'Name'的条目print dictprint(dict.pop('Age')) #删除字典中指定键值对,并返回该键值对的值ret = dict.pop('Class')print(ret)print(dict)a = dict.popitem() #随机删除某组键值对,并以元组方式返回值print(a, dict)dict.clear(); # 清空词典所有条目del dict ; # 删除词典print dict[root@localhost dict]# python dict3.py {'gender': 'man', 'Age': 7, 'weight': 56, 'Class': 'First'}7First{'gender': 'man', 'weight': 56}(('gender', 'man'), {'weight': 56})
改
$ cat dict2.py#!/usr/bin/python#!---coding:utf-8----dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};dict['Age'] = 8; # 修改已存在的键值dict['School'] = "DPS School"; # 增加新的键值对print "dict['Age']: ", dict['Age'];print "dict['School']: ", dict['School'];[root@localhost dict]$ python dict2.py dict['Age']: 8dict['School']: DPS School
查
$ cat dict4.py #!/usr/bin/python#!---coding:utf-8----dict={'age': 18, 'name': 'alex', 'hobby': 'girl'}print(dict['name'])print(list(dict.keys()))print(list(dict.values()))print(list(dict.items()))it = dict.iteritems()print itprint dict.get("name", "girl") print dict.get("e", 18) if "name" in dict: #等同get() print dict["name"]else: print "None"[root@localhost dict]$ python dict4.py alex['hobby', 'age', 'name']['girl', 18, 'alex'][('hobby', 'girl'), ('age', 18), ('name', 'alex')]
创
dict.fromkeys()
$ cat dict5.py #!/usr/bin/pythonseq = ('name', 'age', 'sex')dict = dict.fromkeys(seq)print "New Dictionary : %s" % str(dict)dict = dict.fromkeys(seq, 10)print "New Dictionary : %s" % str(dict)[root@localhost dict]$ python dict5.py New Dictionary : {'age': None, 'name': None, 'sex': None}New Dictionary : {'age': 10, 'name': 10, 'sex': 10}
4设置默认值
$ cat dict6.py #!/usr/bin/python#!---coding:utf-8----dict = {}dict.setdefault("a")print dictdict["a"] = "apple"dict.setdefault("a","default")print dict[root@localhost dict]$ python dict6.py {'a': None}{'a': 'apple'}
5.字典排序
$ cat dict7.py #!/usr/bin/python#!---coding:utf-8----dict = {"a" : "apple", "b" : "grape", "c" : "orange", "d" : "banana"}#按照key排序print sorted(dict.items(), key=lambda d: d[0])#按照value排序 print sorted(dict.items(), key=lambda d: d[1])[root@localhost dict]$ python dict7.py [('a', 'apple'), ('b', 'grape'), ('c', 'orange'), ('d', 'banana')][('a', 'apple'), ('d', 'banana'), ('b', 'grape'), ('c', 'orange')]
6.字典拷贝
浅拷贝
$ cat dict8.py #!/usr/bin/python#!---coding:utf-8----dict = {"a" : "apple", "b" : "grape"}dict2 = {"c" : "orange", "d" : "banana"}dict2 = dict.copy()print dict2[root@localhost dict]$ python dict8.py {'a': 'apple', 'b': 'grape'}
深拷贝
$ cat dict9.py #!/usr/bin/python#!---coding:utf-8----import copydict = {"a" : "apple", "b" : {"g" : "grape","o" : "orange"}}dict2 = copy.deepcopy(dict)dict3 = copy.copy(dict) print(copy1 == copy2) # Trueprint(copy1 is copy2) # Falsedict2["b"]["g"] = "orange" #dict2深拷贝相当于独立objectprint dictdict3["b"]["g"] = "orange"print dict[root@localhost dict]$ python dict9.pyTrueFalse{'a': 'apple', 'b': {'o': 'orange', 'g': 'grape'}}{'a': 'apple', 'b': {'o': 'orange', 'g': 'orange'}}
7.字典遍历
遍历key
cat dict10.oy#!/usr/bin/python#!---coding:utf-8----dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}for k in dict: print kfor k in dict: print k,for key in dict.iterkeys(): print keyfor key in dict.keys(): print key,[root@localhost dict]# python dict10.oy acbda c b d acbda c b d
遍历值
$ cat dict11.py#!/usr/bin/python#!---coding:utf-8----dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}for k in dict: #遍历value print dict[k]for k in dict: #遍历value不换行 print dict[k],for value in dict.itervalues(): print value,for value in dict.values(): # d.values() -> [2, 1, 3] print value[root@localhost dict]$ python dict11.py applegrapebananaorangeapple grape banana orange apple grape banana orange applegrapebananaorange
遍历keys和values
$ cat dict12.py#!/usr/bin/python#!---coding:utf-8----dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}for key, value in dict.iteritems(): # d.iteritems: an iterator over the (key, value) items print key,'corresponds to',dict[key]for key, value in dict.items(): # d.items(): list of d's (key, value) pairs, as 2-tuples # [('y', 2), ('x', 1), ('z', 3)] print key,'corresponds to',value[root@localhost dict]$ python dict12.py a corresponds to applec corresponds to grapeb corresponds to bananad corresponds to orangea corresponds to applec corresponds to grapeb corresponds to bananad corresponds to orange
8.函数字典传参
$ cat dict13.py#!/usr/bin/python#!---coding:utf-8----dic={"m": 1,"n": 2,"q": 3}def dics(qwe): print qwe dics(dic)[root@localhost dict]$ python dict13.py {'q': 3, 'm': 1, 'n': 2}
9.字典推导式
语法一:
key:字典中的keyvalue:字典中的valuedict.items():序列condition:条件表达式key_exp:在for循环中,如果条件表达式condition成立(即条件表达式成立),返回对应的key,value并作key_exp,value_exp处理value_exp:在for循环中,如果条件表达式condition成立(即条件表达式成立),返回对应的key,value并作key_exp,value_exp处理
{key_exp:value_exp for key,value in dict.items() if condition}
语法二:
key:字典中的keyvalue:字典中的valuedict.items():序列condition:条件表达式key_exp:在for循环中,如果条件表达式condition成立(即条件表达式成立),返回对应的key,value并作key_exp,value_exp处理value_exp1:在for循环中,如果条件表达式condition成立(即条件表达式成立),返回对应的key,value并作key_exp,value_exp1处理value_exp2:在for循环中,如果条件表达式condition不成立(即条件表达式不成立),返回对应的key,value并作key_exp,value_exp2处理
{key_exp:value_exp1 if condition else value_exp2 for key,value in dict.items()}
$ cat dict14.py#!/usr/bin/python#!---coding:utf-8----dict1 = {"a":10,"B":20,"C":True,"D":"hello world","e":"python教程"}dict2 = {key:value for key,value in dict1.items() if key.islower()}print(dict2)dict3 = {key.lower():value for key,value in dict1.items() }print(dict3)dict4 = {key:value if key.isupper() else "error" for key,value in dict1.items() }print(dict4)[root@localhost dict]$ python3.8 dict14.py {'a': 10, 'e': 'python教程'}{'a': 10, 'b': 20, 'c': True, 'd': 'hello world', 'e': 'python教程'}{'a': 'error', 'B': 20, 'C': True, 'D': 'hello world', 'e': 'error'}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~