dic = {‘a1‘: 4, 2: ‘2‘, ‘3‘: [1, 2, 3], 4: {1: 10, 2: 20}} #dic = dict(a1=‘4‘,a2=‘5‘) # 清空字典
dic.clear() # 取值 print(dic[‘3‘][1]) # 后面的键会覆盖之前的重复键 print({‘a‘: 12, ‘b‘: 14, ‘a‘: 18}) # 赋值,如果键不存在,就新增这个键 dic[‘bb‘] = ‘666‘ # 设置默认值,并返回添加的键值 print(dic.setdefault(‘55‘, ‘66‘), ‘setdefault‘) # 将序列内的元素当成key,然后依次把key和value一一对应,返回生成的新字典 print(dic.fromkeys([‘a‘, ‘b‘, ‘c‘, ‘d‘], [1, 2, 3, 4]), ‘fromkeys‘) # 获取键值,如果键不存在,就返回默认字符 print(dic.get(‘a2‘, ‘error‘), ‘get‘) # 获取所有键 print(dic.keys(), ‘keys‘) # 获取所有键值 print(dic.values(), ‘values‘) # 获取键值对 print(dic.items(), ‘items‘) # 删除指定键值对,并返回被删除的键值 print(dic.pop(‘a1‘), ‘pop‘) # 随机删除一个键值对,并返回被删除的键值对 print(dic.popitem(), ‘popitem‘) # 更新字典,将其他字典,合并到当前字典,某些序列update,本身不会更新,会将更新后的内容返回 print(dic.update({‘123‘: 134, ‘456‘: 4567}), ‘update‘) # 将[11, 22, 33, 44, 55, 66, 77, 88, 99, 100]列表里面小于60的放到字典keya, 大于等于60的放到keyb templist = [11, 22, 33, 44, 55, 66, 77, 88, 99, 100] tl1 = [] tl2 = [] for i in templist: if i >= 60: tl2.append(i) else: tl1.append(i) dic = {‘a‘: tl1, ‘b‘: tl2} print(dic) exit()
原文:http://www.cnblogs.com/xh4528/p/6497722.html