字典是列表中常用的方法,我们经常处理字典,字典嵌套,很多复杂的操作都来自于基础,只是改变了样式而已,本质是不变的。下面来看看字典中常用的功能都有那些:
1.clear(self)
def clear(self): # real signature unknown; restored from __doc__
""" D.clear() -> None. Remove all items from D. """
pass clear(self)清除字典中的元素,下面来看看一个实例:
>>> d1 = {'k2': 'v2', 'k3': 'v3', 'k1': 'v1'}
>>> d1.clear()
>>> d1
{}
首先,我们定义了一个字典,然后使用clear(self)清除这个字典,clear()清除了字典中所有的键-值对。
2.copy(self)
def copy(self): # real signature unknown; restored from __doc__
""" D.copy() -> a shallow copy of D """
pass
把一个字典赋给另一个变量,我们知道,如果a = b,使用clear()清楚b的内容的时候,a中的内容也会被清除掉。而copy()是新生成了一个变量。
3.fromkeys(*args,**kwargs)
def fromkeys(*args, **kwargs): # real signature unknown
""" Returns a new dict with keys from iterable and values equal to value. """ 生成一个新字典,键(key)不同,值(value)相同。
pass >>> dic = {'k2': 'v2', 'k3': 'v3', 'k1': 'v1'}
>>> new_dic = dic.fromkeys(["k1"],"v1")
>>> new_dic
{'k1': 'v1'}
>>> n_dic = dic.fromkeys(["k1","k2","k3","k4"],"v1")
>>> n_dic
{'k4': 'v1', 'k2': 'v1', 'k3': 'v1', 'k1': 'v1'}
>>> d1 = dic.fromkeys(["k1","k2"],"v3")
>>> d1
{'k2': 'v3', 'k1': 'v3'}
4.get(self,k,d=None)
def get(self, k, d=None): # real signature unknown; restored from __doc__
""" D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """
pass
get(self,k,d=None)获取字典中的键,返回对应的值,如果键不存在,则返回d=None,默认是None,我们也可以自己定义,如果获取不到会怎样,下面我们来看两个例子:
我们知道,可以通过键得到对应的值:
1.直接获取值
>>> dic = {'k2': 'v2', 'k3': 'v3', 'k1': 'v1'}
>>> dic["k1"]
'v1'
>>> dic["k2"]
'v2'
>>> dic["k4"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'k4'
我们知道,如果字典中存在键,一定会返回对应的值,"k4"不存在字典中,结果报错,说键值错误dic[key]=value.
2.使用get(self,k,d=None)获取值
>>> dic = {'k2': 'v2', 'k3': 'v3', 'k1': 'v1'}
>>> dic.get("k1")
'v1'
>>> dic.get("k2")
'v2'
>>> dic.get("k4")
>>> None
>>> dic.get("k4","alexsb") (1)
'alexsb'
如果字典中存在指定的键,那么就会返回对应的值;我们知道"k4"不存在于字典中,使用get(self,k,d=None)没有报错,返回None,我们也可以自己定义返回值,(1)处,我们设定当"k4"不存在的时候返回"alexsb",由于"k4"不存在,因而返回"alexsb".
5.items(self)
def items(self): # real signature unknown; restored from __doc__
""" D.items() -> a set-like object providing a view on D's items """ """返回字典中的键-值对
pass items(self)返回字典中的键-值对,示例如下:
>>> dic = {'k2': 'v2', 'k3': 'v3', 'k1': 'v1'}
>>> dic.items()
dict_items([('k2', 'v2'), ('k3', 'v3'), ('k1', 'v1')])
6.keys(self)
def keys(self): # real signature unknown; restored from __doc__
""" D.keys() -> a set-like object providing a view on D's keys """
pass keys(self)返回字典中的键值,实例如下:
>>> dic = {'k2': 'v2', 'k3': 'v3', 'k1': 'v1'}
>>> dic.keys()
dict_keys(['k2', 'k3', 'k1'])
>>> type(dic.keys())
<class 'dict_keys'>
7.values(self)
def values(self): # real signature unknown; restored from __doc__
""" D.values() -> an object providing a view on D's values """
pass values(self)返回字典中的值,实例如下:
>>> dic = {'k2': 'v2', 'k3': 'v3', 'k1': 'v1'}
>>> dic.values()
dict_values(['v2', 'v3', 'v1'])
8.pop(self,k,d=None)
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
由于字典是无序的,因此必须指定删除哪个值,pop(self,k,d=None),下面来看一下:
>>> dic = {'k2': 'v2', 'k3': 'v3', 'k1': 'v1'}
>>> dic.pop()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: pop expected at least 1 arguments, got 0
上面我们使用pop()删除字典元素的时候,提示错误,至少需要一个参数,但是我们没有提供,要记住,字典是无序的,没有顺序,因此必须我们指定键值,告诉字典删除哪个键值的元素。
>>> dic = {'k2': 'v2', 'k3': 'v3', 'k1': 'v1'}
>>> dic.pop("k3")
'v3'
>>> dic.pop("k4")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'k4'
>>> dic.pop("k4","alexsb")
'alexsb'
在上面,我们使用pop(self,k,d=None)删除字典中的元素,必须指定键值;如果键值不存在,则会提示KeyError:"k4",我们也可以指定当键值不存在的时候返回什么值,我们在上面设置,当键值不存在的时候返回"alexsb",由于"k4"不存在,因此,因此输出提示"alexsb"
9.popitem(self)
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
popitem(self)由于字典是无序的,popitem(self)没有指定参数,因此是随机删除字典中的元素,下面我们来看一下:
dic = {'k4': 'v4', 'k2': 'v2', 'k3': 'v3', 'k1': 'v1'}
dic.popitem())
打印出来的结果时随机变动的,一会删除"k4",一会"k1"没有规律,因此popitem(self)是随机删除字典中的元素。
10.setdefault(self,k,d=None)
def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
""" D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
pass setdefault(self,k,d=None)向字典中加入键-值对,如果没有指定值,那么默认值为None,示例如下:
>>> dic = {'k4': 'v4', 'k2': 'v2', 'k3': 'v3', 'k1': 'v1'}
>>> dic.setdefault("k5")
>>> dic
{'k5': None, 'k4': 'v4', 'k2': 'v2', 'k3': 'v3', 'k1': 'v1'}
>>> dic.setdefault("k6","sb")
'sb'
>>> dic
{'k2': 'v2', 'k5': None, 'k6': 'sb', 'k4': 'v4', 'k3': 'v3', 'k1': 'v1'}
可以看出,当我们向列表中插入元素时,使用setdefault(self,k,d=None)时,如果没有定义值,那么就默认是None。否则,等价于dict[key] = value.
11.update(self,E=None,**F)
def update(self, E=None, **F): # known special case of dict.update
"""
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 update(self,E=None,**F)更新列表中的值,也可以用在添加新的键-值对进来,示例如下:
>>> dic = {'k2': 'v2', 'k3': 'v3', 'k1': 'v1'}
>>> dic.update({"k5":123})
>>> dic
{'k2': 'v2', 'k5': 123, 'k3': 'v3', 'k1': 'v1'}
>>> dic.update({"k5":456})
>>> dic
{'k2': 'v2', 'k5': 456, 'k3': 'v3', 'k1': 'v1'} >>> dic = {'k2': 'v2', 'k3': 'v3', 'k1': 'v1'}
>>> dic.update({"k4":"v4","k5":123})
>>> dic
{'k2': 'v2', 'k5': 123, 'k4': 'v4', 'k3': 'v3', 'k1': 'v1'}
可以使用update()向字典中添加字典,即把另外一个字典中的键-值对添加到这个字典中的键值对。
更新字典中的键值对,必须以字典的形式进行跟新。
12.__contains__(self,*args,**kwargs)
def __contains__(self, *args, **kwargs): # real signature unknown
""" True if D has a key k, else False. """
pass __contains__(self,*args,**kwargs)查看字典中是否包含特定的键值对,实例如下:
>>> dic = {'k2': 'v2', 'k5': 123, 'k4': 'v4', 'k3': 'v3', 'k1': 'v1'}
>>> dic.__contains__("k1")
True
>>> dic.__contains__("v2")
False
__contains__(self,*args,**kwargs)判断字典中是否包含指定的键值,在字典中键是唯一的,所以查找包含都是对键的操作。
13.__delitem__(self,*args,**kwargs)
def __delitem__(self, *args, **kwargs): # real signature unknown
""" Delete self[key]. """
pass >>> dic = {'k2': 'v2', 'k5': 123, 'k4': 'v4', 'k3': 'v3', 'k1': 'v1'}
>>> dic.__delitem__("k4")
>>> dic
{'k2': 'v2', 'k5': 123, 'k3': 'v3', 'k1': 'v1'}
14.__getattribute__(self,*args,**kwargs)
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
15.__getitem__(self,y)
def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """ """获取字典中指定键的值"""
pass >>> dic = {'k2': 'v2', 'k5': 123, 'k3': 'v3', 'k1': 'v1'}
>>> dic.__getitem__("k5")
123
16.__iter__(self,*args,**kwargs)
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
17.__len__(self,*args,**kwargs)
def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass __len__(self,*args,**kwargs)统计字典的长度,等价于len(dict),示例如下:
>>> dic = {'k2': 'v2', 'k5': 123, 'k3': 'v3', 'k1': 'v1'}
>>> dic.__len__()
4
>>> len(dic)
4
18.__new__(*args,**kwargs)
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
19.__repr__(self,*args,**kwargs)
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
20.__setitem__(self,*args,**kwargs)
def __setitem__(self, *args, **kwargs): # real signature unknown
""" Set self[key] to value. """
pass __setitem__(self,k,v)向字典中添加元素,必须指定键和值,否则会报错,如下:
>>> dic = {'k2': 'v2', 'k5': 123, 'k6': 666, 'k1': 'v1'}
>>> dic.__setitem__("k7")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected 2 arguments, got 1
可以看出,__setitem__(self,k,v)需要两个参数,但是我们只提供了一个参数给它。
>>> dic = {'k2': 'v2', 'k5': 123, 'k1': 'v1'}
>>> dic.__setitem__("k6",666)
>>> dic
{'k2': 'v2', 'k5': 123, 'k6': 666, 'k1': 'v1'}