标签:python
In [43]: a = dict(k1=‘v1‘,k2=‘v2‘) In [44]: type(a) Out[44]: dict In [45]: a Out[45]: {‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘} #这个方法和a这个字典没关系呀,没看懂。实际上就是生成新的字典。 In [47]: new_a = a.fromkeys([‘k‘],‘v‘) In [48]: new_a Out[48]: {‘k‘: ‘v‘} In [49]: new_a = a.fromkeys([‘k‘,‘w‘],‘v‘) In [50]: new_a Out[50]: {‘k‘: ‘v‘, ‘w‘: ‘v‘} #get方法。输入key,输出对应的value In [54]: a.get(‘k1‘) Out[54]: ‘v1‘ In [57]: a.get(‘k3‘,‘vv‘) #如果输入一个不存在的key,就返回NONE,或者可以指定返回的值 Out[57]: ‘vv‘ In [59]: a.keys() Out[59]: dict_keys([‘k1‘, ‘k2‘]) In [60]: type(a.keys()) Out[60]: dict_keys In [61]: a.values() Out[61]: dict_values([‘v1‘, ‘v2‘]) In [62]: a.items() Out[62]: dict_items([(‘k1‘, ‘v1‘), (‘k2‘, ‘v2‘)]) #用for循环输出key,输出的是字符串 In [65]: for k in a.keys(): ...: print(k) ...: print(type(k)) ...: k1 <class ‘str‘> k2 <class ‘str‘> #输出的是元组 In [66]: for k in a.items(): ...: print(k) ...: print(type(k)) ...: (‘k1‘, ‘v1‘) <class ‘tuple‘> (‘k2‘, ‘v2‘) <class ‘tuple‘> In [68]: for k,v in a.items(): ...: print(k,v) ...: k1 v1 k2 v2 #pop方法需要输入参数,指定删除一个key的键值对。不写参数会报错 In [71]: a.pop(‘k1‘) Out[71]: ‘v1‘ In [72]: a Out[72]: {‘k2‘: ‘v2‘} #popitem不需要输入参数,随机pop一个。 In [76]: a Out[76]: {‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘} In [77]: a.popitem() Out[77]: (‘k2‘, ‘v2‘) In [78]: a Out[78]: {‘k1‘: ‘v1‘} #添加一个键值对 In [80]: a[‘k3‘]=‘v3‘ In [81]: a Out[81]: {‘k1‘: ‘v1‘, ‘k3‘: ‘v3‘} #update也是添加 In [93]: a Out[93]: {‘k1‘: ‘v1‘, ‘k3‘: ‘v3‘, ‘k4‘: ‘v4‘, ‘k5‘: ‘v5‘} In [94]: a.update({‘k2‘:‘v2‘}) In [95]: a Out[95]: {‘k1‘: ‘v1‘, ‘k2‘: ‘v2‘, ‘k3‘: ‘v3‘, ‘k4‘: ‘v4‘, ‘k5‘: ‘v5‘}
标签:python
原文地址:http://chomper.blog.51cto.com/7866214/1934341