第十六节,基本数据类型,字典dict
Posted 林贵秀
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第十六节,基本数据类型,字典dict相关的知识,希望对你有一定的参考价值。
字典
常用操作:
索引
新增
删除
键、值、键值对
循环
长度
字典由键值对组成,由一个键(名称)和 一个值组成,与列表和元组不同的是里面的元素是有键的(名称)
所以当要打印字典时,打印字典变量加[键]即可
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = { 4 "zhs":"1", 5 "ls":"2", 6 "ww":"3" 7 } 8 print(a["ls"]) 9 #打印出 2 打印出了ls键的值
创建字典
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = {"zhs":"1", "ls":"2", "ww":"3"} 4 #或者 5 a = dict({"zhs":"1", "ls":"2", "ww":"3"}) 6 #或者 7 a = { 8 "zhs":"1", 9 "ls":"2", 10 "ww":"3" 11 } 12 #一般采用第三中,更容易读
索引
打印字典变量加[要打印的键]
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = { 4 "zhs":"1", 5 "ls":"2", 6 "ww":"3" 7 } 8 print(a["ls"]) 9 print(a["ww"]) 10 #打印出 2 3 打印出了ls和ww键的值
for循环
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = { 4 "zhs":"1", 5 "ls":"2", 6 "ww":"3" 7 } 8 for b in a: 9 print(b) 10 #打印出 ww zhs ls 默认循环出的是字典的键 11 12 a = { 13 "zhs":"1", 14 "ls":"2", 15 "ww":"3" 16 } 17 for b in a: 18 print(a[b]) 19 #打印出 3 1 2 要打印字典变量加上[自定义循环变量,也就是键]才能打印出值
keys(self)
"""(获取字典的键)""":返回一个字典的键列表
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = { 4 "zhs":"1", 5 "ls":"2", 6 "ww":"3" 7 } 8 print(a.keys()) 9 #打印出 [\'ww\', \'zhs\', \'ls\'] 返回字典键列表
values(self)
"""(获取字典的值)""":返回一个字典的值列表
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = { 4 "zhs":"1", 5 "ls":"2", 6 "ww":"3" 7 } 8 print(a.values()) 9 #打印出 [\'3\', \'1\', \'2\'] 返回字典值列表
items(self)
"""(获取字典里的键和值)""":返回一个字典的键和值列表加元组
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = { 4 "zhs":"1", 5 "ls":"2", 6 "ww":"3" 7 } 8 print(a.items()) 9 #打印出 [(\'ww\', \'3\'), (\'zhs\', \'1\'), (\'ls\', \'2\')] 返回字典里的键和值列表加元组
(keys:获取键) (values:获取值) (items:获取键和值) 结合for循环
(keys:获取键)结合for循环
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = { 4 "zhs":"1", 5 "ls":"2", 6 "ww":"3" 7 } 8 for b in a.keys(): 9 print(b) 10 #打印出 ww zhs ls 循环出了字典的键
(values:获取值)结合for循环
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = { 4 "zhs":"1", 5 "ls":"2", 6 "ww":"3" 7 } 8 for b in a.values(): 9 print(b) 10 #打印出 3 1 2 循环出了字典的值
(items:获取键和值)结合for循环
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = { 4 "zhs":"1", 5 "ls":"2", 6 "ww":"3" 7 } 8 for k, v in a.items(): #因为items()获取的键和值,所以循环里要自定义两个变量分别代表键和值 9 print(k) 10 print(v) 11 #打印出 ww 3 zhs 1 ls 2 循环出了字典的键和值
clear(self)
"""(清除字典里的所有内容)"""
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = { 4 "zhs":"1", 5 "ls":"2", 6 "ww":"3" 7 } 8 a.clear() 9 print(a) 10 #打印出 {} 字典里是空的
get(self, k, d=None)(推荐使用)
""" (根据key(键)获取值,如果key(键)不存在可以指定默认值 )""":如果键后面指定了默认值,键存在就获取键自身的值,如果键不存在就获取默认值
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = { 4 "zhs":"1", 5 "ls":"2", 6 "ww":"3" 7 } 8 print(a.get("ls")) 9 #打印出 2 输出指定键的值 10 11 a = { 12 "zhs":"1", 13 "ls":"2", 14 "ww":"3" 15 } 16 print(a.get("xyz","123")) #xyz键不存在,就获取默认值123 17 #打印出 123 输出指定键的值,如果指定键不存在就输出默认值
has_key(self, k)
注意:python3版本以上已经取消了
""" (:键)key:键,名称 """:返回真或者假
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = { 4 "zhs":"1", 5 "ls":"2", 6 "ww":"3" 7 } 8 print(a.has_key("ls")) 9 #打印出 True 返回真说明字典里有ls这个键
判断字典里是否有某个key键:返回真或者假
也可以判断字典里是否有某个值
注意:python3版本以上使用这个方法替代已经取消的has_key
格式:"要判断的键" in 字典变量.keys()
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = { 4 "zhs":"1", 5 "ls":"2", 6 "ww":"3" 7 } 8 b = "ls" in a.keys() 9 print(b) 10 #打印出 True 返回真说明字典里有ls这个键 11 12 a = { 13 "zhs":"1", 14 "ls":"2", 15 "ww":"3" 16 } 17 b = "2" in a.values() 18 print(b) 19 #打印出 True 返回真说明字典里有2这个值
update(self, E=None, **F)
""" (追加更新)"""要追加更新的变量
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = { 4 "zhs":"1", 5 "ls":"2", 6 "ww":"3" 7 } 8 b = { 9 "z":"4", 10 "l":"5", 11 "w":"6" 12 } 13 a.update(b) 14 print(a) 15 #打印输出 {\'ww\': \'3\', \'zhs\': \'1\', \'ls\': \'2\', \'w\': \'6\', \'z\': \'4\', \'l\': \'5\'} 将b字典追加更新到了a字典
追加更新 2
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #这个方法是。如果字典里存在k4这个键就987的值更新给k4键,如果不存在k4键就在字典里创建k4键值为987 4 a = { 5 "k1":123, 6 "k2":456, 7 "k3":789, 8 } 9 a["k4"] = 987 10 print(a)
删除字典里的元素
格式:del 字典变量.[要删除的元素键]
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 a = { 4 "zhs":"1", 5 "ls":"2", 6 "ww":"3" 7 } 8 del a["ls"] 9 print(a) 10 #打印输出 {\'ww\': \'3\', \'zhs\': \'1\'} 删除了ls键这个元素
fromkeys(*args, **kwargs)
"""(查找字典里一个或多个元素的键,将查找的键重新指定新的值)要查找的元素键,要改变的新值"""
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 #fromkeys 查找字典里一个或多个元素的键,将查找的键重新指定新的值 4 a = {"k1":123, "k2":456, "k3":789} 5 b = a.fromkeys(["k1", "k2", "k3"], "876") 6 print(b) 7 #输出 {\'k2\': \'876\', \'k3\': \'876\', \'k1\': \'876\'}
class dict(object): """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object\'s (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) """ def clear(self): # real signature unknown; restored from __doc__ """ 清除内容 """ """ D.clear() -> None. Remove all items from D. """ pass def copy(self): # real signature unknown; restored from __doc__ """ 浅拷贝 """ """ D.copy() -> a shallow copy of D """ pass @staticmethod # known case def fromkeys(S, v=None): # real signature unknown; restored from __doc__ """ dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. v defaults to None. """ pass def get(self, k, d=None): # real signature unknown; restored from __doc__ """ 根据key获取值,d是默认值 """ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass def has_key(self, k): # real signature unknown; restored from __doc__ """ 是否有key """ """ D.has_key(k) -> True if D has a key k, else False """ return False def items(self): # real signature unknown; restored from __doc__ """ 所有项的列表形式 """ """ D.items() -> list of D\'s (key, value) pairs, as 2-tuples """ return [] def iteritems(self): # real signature unknown; restored from __doc__ """ 项可迭代 """ """ D.iteritems() -> an iterator over the (key, value) items of D """ pass def iterkeys(self): # real signature unknown; restored from __doc__ """ key可迭代 """ """ D.iterkeys() -> an iterator over the keys of D """ pass def itervalues(self): # real signature unknown; restored from __doc__ """ value可迭代 """ """ D.itervalues() -> an iterator over the values of D """ pass def keys(self): # real signature unknown; restored from __doc__ """ 所有的key列表 """ """ D.keys() -> list of D\'s keys """ return [] def pop(self, k, d=None): # real signature unknown; restored from __doc__ """ 获取并在字典中移除 """ """ D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ pass def popitem(self): # real signature unknown; restored from __doc__ """ 获取并在字典中移除 """ """ D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. """ pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """ """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ pass def update(self, E=None, **F): # known special case of dict.update """ 更新 {\'name\':\'alex\', \'age\': 18000} [(\'name\',\'sbsbsb\'),] """ """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] """ pass def values(self): # real signature unknown; restored from __doc__ """ 所有的值 """ """ D.values() -> list of D\'s values """ return [] def viewitems(self): # real signature unknown; restored from __doc__ """ 所有项,只是将内容保存至view对象中 """ """ D.viewitems() -> a set-like object providing a view on D\'s items """ pass def viewkeys(self): <以上是关于第十六节,基本数据类型,字典dict的主要内容,如果未能解决你的问题,请参考以下文章