字典练习
dic = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'} # 1.遍历出所有的key for key in dic: print(key) # 2.遍历出所有的value for key in dic: print(dic[key]) # 3.遍历出所有的key和value for key in dic: print(key, dic[key]) for key, value in dic.items(): #效率低 print(key, value) # 4.在字典添加一个键值对,’k4’:’v4’,输出添加后的字典 dic['k4'] = 'v4' print(dic) # 5.删除键值对'k1','v1'并输出 dic.pop('k1') del dic['k1'] dic.popitem() # 随机返回并删除字典中的一对键和值(一般删除末尾对)。 print(dic) # 6.删除字典中的键'k5'对应的键值对,如果字典不存在键'k5',则不报错,并且让其返回None if dic.get('k5'): dic.pop('k5') else: print(dic.get('k5')) # 7.请获取字典中k2对应的值 k2_value = dic.get('k2') print(k2_value) # 8.请获取字典中'k6'对应的值,如果键'k6'不存在,则不报错,并且让其返回None k6_value = dic.get('k6') if not k6_value: print(k6_value) # 9.现有dic2 ={‘k1’:’v111’,’a’:’b’}通过一行操作使dic2 = {‘k1’:’v1’,’k2’:’v2’,’k3’:’v3’,a’:’b’} dic2 = {'k1': 'v111', 'a': 'b'} dic2.update({'k1': 'v1', 'k2': 'v2', 'k3': 'v3', 'a': 'b'}) print(dic2) # 10 组合嵌套题 lis = [['k', ['qwe', 20, {'k1': ['tt', 3, '1']}, 89], 'ab']] # a.将列表list中的'tt'变成大写(用两种方式) lis[0][1][2]['k1'][0] = 'TT' print(lis) lis[0][1][2]['k1'].remove('tt') lis[0][1][2]['k1'].insert(0, 'TT') print(lis) lis[0][1][2]['k1'][0] = lis[0][1][2]['k1'][0].upper() print(lis) # b.将列表list中的数字3变成字符串'100'(用两种方式) lis[0][1][2].update({'k1': ['tt', '100', '1']}) print(lis) lis[0][1][2]['k1'][1] = '100' print(lis) lis[0][1][2]['k1'][1] = lis[0][1][2]['k1'][1] lis[0][1][2]['k1'].remove(3) lis[0][1][2]['k1'].insert(1, '100') print(lis) # c.将列表list中的字符串'1'变成数字101(用两种方式) lis[0][1][2]['k1'][2] = 101 print(lis) lis[0][1][2]['k1'][2] = int(lis[0][1][2]['k1'][2].replace('1', '101')) print(lis) # 总结:就是从三个层面修改:1.列表 2.字典 3.字符串
li = [1, 2, 3, 'a', 'b', 4, 'c'] dic = {} dic.setdefault('k1', []) for odd in li: if li.index(odd) % 2 != 0: dic['k1'].append(odd) print(dic)