这一节,我来介绍字典里面的方法,首先先回顾下什么是字典类型的数据类型。
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)
"""
# **kwargs -- 关键字
# mapping -- 元素的容器。
# iterable -- 可迭代对象。
其中提到了三种参数,关键字,迭代器,和映射关系。字典这个数据类型就好比我们儿时用的纸质版字典一样,有key(关键字--在纸质版字典中叫页数),有value(值,在纸质版字典中叫目的字符)。不同于纸质版字典的一点就是,dict中的key 和 value 是一一对应的关系,然后value的数据类型可以有好多种,比如list、str等等。二者可以互相取到对方,根据value取对应的key,根据key取对应的value。
目录 ( 这是这一章节的要点内容 )
介绍dict 下面第一个方法。
1、clear
clear()这个方法在之前的str 和 list中间都存在,清空集合内所有元素。
a = {"k":"v","k1":"1,2,3","k2,k3":"[1,2,3,4]"}
print(a) # {'k': 'v', 'k1': '1,2,3', 'k2,k3': '[1,2,3,4]'}
print(type(a)) # <class 'dict'>
print(a.clear()) # None
其中的【1,2,3,4】为list类型。也能作为value来储存。
2、copy
copy()这个方法和上面的clear方法在python其他数据类型中也有使用,复制一个字典与原字典类型相同。相当于在内存中重新开辟一个空间来存放被copy对象。
dict.copy()
""" D.copy() -> a shallow copy of D """
a = {"name":"Charles","age":"10"}
b = a.copy()
print(a, type(a), id(a)) # {'name': 'Charles', 'age': '10'} <class 'dict'> 2172766734304
print(b, type(b), id(b)) # {'name': 'Charles', 'age': '10'} <class 'dict'> 2172766734376
3、fromkeys
fromkeys()返回一个新dict,keys来自iterable,value来自equal。其中iterable是第一个参数,必须加上;value为第二个参数,可加可不加,默认为None。fromkeys中的数据类可以是list、tuple、set。
def fromkeys(*args, **kwargs): # real signature unknown
""" Returns a new dict with keys from iterable and values equal to value. """
pass
dict1 = dict.fromkeys(["Dict", "List", "Str"])
print(dict1) # {'Dict': None, 'List': None, 'Str': None}
dict1 = dict.fromkeys(("Dict", "List", "Str"))
print(dict1) # {'Dict': None, 'List': None, 'Str': None}
dict3 = dict.fromkeys([1,2,3],['one','two','three'])
print(dict3) # {1: ['one', 'two', 'three'], 2: ['one', 'two', 'three'], 3: ['one', 'two', 'three']}
4、get
get()方法根据key取对应的value。get()一次只能对应取出一个value。
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
a = {'1':'Dict','2':'List',3:'Str'}
print(a.get('2')) # List
print(a.get(3)) # Str
5、item
item()方法利用key和value来访问字典。
def items(self): # real signature unknown; restored from __doc__
""" D.items() -> a set-like object providing a view on D's items """
pass
a = {1:'Dict' , 2:'List' , 3:'Str'}
for k,v in a.items():
print(k,v)
# 1 Dict
# 2 List
# 3 Str
6、keys
keys()方法可以取出dict中所有的keys值,并存放至类似于list的一个列表中。
def keys(self): # real signature unknown; restored from __doc__
""" D.keys() -> a set-like object providing a view on D's keys """
pass
a = {1:'Dict' , 2:'List' , 3:'Str'}
print(a.keys(), type(a.keys()))
# dict_keys([1, 2, 3]) <class 'dict_keys'>
7、pop
pop()方法,删除指定key所对应的value。必须带上指定的key值,否则报错。
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
a = {1:'Dict' , 2:'List' , 3:'Str' , 4:'Tuple'}
print(a.pop(1)) # Dict
print(a) # {2: 'List', 3: 'Str', 4: 'Tuple'}
8、popitem
popitem()方法和pop()方法类似,都是用于删除字典里面的元素,但是popitem删除的为默认删除字典中的最后一项元素,不能带参数。
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
a = {1:'Dict' , 2:'List' , 3:'Str' , 4:'Tuple'}
print(a.popitem()) # (4, 'Tuple')
print(a.popitem(), type(a.popitem())) # (3, 'Str')<class 'tuple'>
print(a) # {1: 'Dict', 2: 'List'}
9、setdefault
setdefault()和get()方法类似,都是在字典中根据指定的key值取出对应的value值。
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
a = {1:'Dict' , 2:'List' , 3:'Str' , 4:'Tuple'}
print(a.setdefault(5))
print(a)
# None
# {1: 'Dict', 2: 'List', 3: 'Str', 4: 'Tuple', 5: None}
a = {1:'Dict' , 2:'List' , 3:'Str' , 4:'Tuple'}
print(a.get(5))
print(a)
# None
# {1: 'Dict', 2: 'List', 3: 'Str', 4: 'Tuple'}
不同点在于:get()指定了一个在字典中不存在的key值,返回值为None,对原dict无改变;setdefault()指定了一个在字典中不存在的key值,返回值为None。但对原dict改变,增加原dict不存在的key值。并自动补上value默认值:None,生成新dict。
10、update
update()为一个更新操作,有相同的key在原dict中,则会被替换,无相同的key在原dict中则新增。
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
# 替换
a = {1:'Dict' , 2:'List' , 3:'Str' , 4:'Tuple'}
b = {1:'set'}
a.update(b)
print("替换后的dict为:{}".format(a)) # 替换后的dict为:{1: 'set', 2: 'List', 3: 'Str', 4: 'Tuple'}
# 新增
a = {1:'Dict' , 2:'List' , 3:'Str' , 4:'Tuple'}
b = {5:'set'}
a.update(b)
print("新增后的dict为:{}".format(a)) # 新增后的dict为:{1: 'Dict', 2: 'List', 3: 'Str', 4: 'Tuple', 5: 'set'}
11、values
values()和之前提到的keys()相似,values将dict中已有的values组成一个list 的列表返回输出。
def values(self): # real signature unknown; restored from __doc__
""" D.values() -> an object providing a view on D's values """
pass
a = {1: 'Dict', 2: 'List', 3: 'Str', 4: 'Tuple', 5: 'set'}
print(a.values()) # dict_values(['Dict', 'List', 'Str', 'Tuple', 'set'])
吐槽下:昨天晚上写了一小时,不知道为什么没有保存成功,今天又写了一遍。