在 Python 中, 字典 是一系列 键 — 值对 。每个键都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何 Python 对象用作字典中的值
可以用如下的几种方式定义字典:
dic = {‘color‘: ‘green‘, ‘points‘: 5} dic1 = dict(color = ‘green‘, points = 5) dic2 = dict([(‘color‘, ‘green‘), (‘points‘, 5)])
字典推导式可以从任意的键值表达式中创建字典
dic = {var:var**2 for var in range(2, 11, 2)} print(dic) # {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
在字典中循环时,关键字和对应的值可以使用 items()方法同时解读出来:
dic = {‘color‘: ‘green‘, ‘points‘: 5} for key, value in dic.items(): print(key, value) # 输出 # color green # points 5
也可以使用keys()方法只取出字典中的键,使用values()方法取出字典中的值
def clear(self): # 无返回值,删除字典中所有的项 """ D.clear() -> None. Remove all items from D. """ pass def copy(self): # 对字典的浅复制 """ D.copy() -> a shallow copy of D """ pass def fromkeys(*args, **kwargs): # 函数用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值 """ Returns a new dict with keys from iterable and values equal to value. """ pass def get(self, k, d=None): # 返回给定键值的值,如果不存在返回None """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass def items(self): # 返回键——值对列表 """ D.items() -> a set-like object providing a view on D‘s items """ pass def keys(self): # 返回键列表 """ D.keys() -> a set-like object providing a view on D‘s keys """ pass def pop(self, k, d=None): # 删除给定的键——值对,并返回该键所对应的值,如果不存在产生一个KeyError错误 """ 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): # 删除某个键——值对,并该其键值对返回,随机删除,如果空,返回KeyError错误 """ 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): # 如果 key 在 字典中,返回对应的值。如果不在字典中,则插入 key 及设置的默认值 default,并返回 default ,default 默认值为 None。 """ 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): # 把字典dict2的键/值对更新到dict里 """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then 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): # 返回字典值列表 """ D.values() -> an object providing a view on D‘s values """ pass
原文:https://www.cnblogs.com/dengcz/p/8996873.html