说字典方法之前,我们先来说几个巧用字典取值的方法
1:
d = {'name':'zhang','age':25,'job':'IT'}
### 第一种方法
for key1in d:
print(key1,d[key1])
#### 输出结果
age 25
job IT
name zhang
2:
d = {'name':'zhang','age':25,'job':'IT'} ### 第二种方法 for k,v in d.items(): print("dict[%s] = " %k,v) ### 输出结果 dict[job] = IT dict[age] = 25 dict[name] = zhang
dict 类方法,不再细说
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) """
2:clear ---: 清空,返回空列表’{}’
def clear(self): # real signature unknown; restored from __doc__ """ D.clear() -> None. Remove all items from D. """ pass
使用方法:
d = {'name':'zhang','age':25,'job':'IT'} d1 = d.clear() print(d) ### 输出结果 {}
3:copy ----: 浅拷贝
def copy(self): # real signature unknown; restored from __doc__ """ D.copy() -> a shallow copy of D """ pass
使用方法:
d = {'name':'zhang','age':25,'job':'IT'} d1 = d.copy() print(d1) ### 输出结果 {'name': 'zhang', 'job': 'IT', 'age': 25}
4: fromkeys ---:创建并返回一个新字典,以seq中的元素做该字典的键,val做该字典中所有键对应的初始值
def fromkeys(*args, **kwargs): # real signature unknown """ Returns a new dict with keys from iterable and values equal to value. """ pass
使用方法:
print(d1.fromkeys('name','zhang')) ### 输出结果 {'n': 'zhang', 'm': 'zhang', 'a': 'zhang', 'e': 'zhang'}
5: get ---: 获取值;对字典dict中的键key,返回它对应的值value,如果字典中不存在此键,则返回default值
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
使用方法:
d = {'name':'zhang','age':25,'job':'IT'} #d1 = {} #print(d1.fromkeys('name','zhang')) print(d.get('name')) print(d.get('Height')) ### 输出结果 zhang None
6: items ---: 返回一个包含字典中键、值对元组的列表
def items(self): # real signature unknown; restored from __doc__ """ D.items() -> a set-like object providing a view on D's items """ pass
使用方法:
d = {'name':'zhang','age':25,'job':'IT'} print(d.items()) ### 输出结果 dict_items([('name', 'zhang'), ('job', 'IT'), ('age', 25)])
7: key ---: 返回所有的key
def keys(self): # real signature unknown; restored from __doc__ """ D.keys() -> a set-like object providing a view on D's keys """ pass
使用方法:
d = {'name':'zhang','age':25,'job':'IT'} print(d.keys()) ### 输出结果 dict_keys(['name', 'age', 'job'])
8:values ---: 返回所有的value
def values(self): # real signature unknown; restored from __doc__ """ D.values() -> an object providing a view on D's values """ pass
使用方法:
d = {'name':'zhang','age':25,'job':'IT'} print(d.values()) ### 输出结果 dict_values(['IT', 25, 'zhang'])
9: pop ---: 删除指定的key,并返回相应的值,如果没有此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
使用方法:
d = {'name':'zhang','age':25,'job':'IT'} d1 = d.pop('name') print(d) print(d1) ### 输出结果 {'age': 25, 'job': 'IT'} zhang
10: 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
使用方法:
d = {'name':'zhang','age':25,'job':'IT'} print(d) print(d.popitem()) print(d) ### 输出结果 {'age': 25, 'name': 'zhang', 'job': 'IT'} ('age', 25) {'name': 'zhang', 'job': 'IT'}
11: setdefault ---: 如果key 值存在则返回其值,如果不存在则添加此key ,默认以None作为其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
使用方法:
d = {'name':'zhang','age':25,'job':'IT'} print(d.setdefault('name')) d1 = d.setdefault(('Height')) print(d) ### 输出结果 zhang {'name': 'zhang', 'job': 'IT', 'Height': None, 'age': 25}
12: update ---: 更新
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
使用方法:
d = {'name':'zhang','age':25,'job':'IT'} d1 = {'Height':'170'} d3 = d.update(d1) print(d) ### 输出结果 {'Height': '170', 'age': 25, 'name': 'zhang', 'job': 'IT'}
测试小程序
有如下值集合[11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66 , 'k2':小于66}
心得:实现方法可能有很多,请吐槽
l = [11,22,33,44,55,66,77,88,99,90,] d = {} l1 = [] l2 = [] for i in l: if i > 66: l2 = l1.append(i) d1 = d.setdefault('key1',l1) if i < 66: l3 = l2.append(i) d1 = d.setdefault('key2',l2) print(d) #### 输出结果 {'key1': [77, 88, 99, 90], 'key2': [11, 22, 33, 44, 55]}