5 1 # 创建字典 6 2 d=dict(name='lily',age=18,phone='188011514000') 7 3 print(d)
8 4 # {'name': 'lily', 'age': 18, 'phone': '188011514000'} 9 5 10 6 # 通过key获取对应vlaue 11 7 name =d['name'] 12 8 print(name) 13 9 # lily 14 10 15 11 # in,not in 判断key是否存在 16 12 if 'name' in d: 17 13 print('name is exist') 18 14 else: 19 15 print('no') 20 16 21 17 # 获取字典所有的key 22 18 keys = d.keys() 23 19 print(keys) 24 20 # dict_keys(['name', 'age', 'phone']) 25 21 26 22 # dict.values() 返回一个包含字典所有value的列表 27 23 vlaue = d.values() 28 24 print(vlaue) 29 25 # dict_values(['lily', 18, '188011514000']) 30 26 31 27 # dict.items()返回一个包含所有(键,值)元组的列表 32 28 keyandvlaue = d.items() 33 29 print(keyandvlaue) 34 30 # dict_items([('name', 'lily'), ('age', 18), ('phone', '188011514000')]) 35 31 36 32 # dict.fromkeys(seq, val=None) 创建并返回一个新字典,以seq中的元素做该字典的键,val做该字典中所有键对应的初始值(默认为None) 37 33 lk =['xiao','da','hong'] 38 34 dic = dict.fromkeys(lk) 39 35 print(dic) 40 36 # {'xiao': None, 'da': None, 'hong': None} 41 42 43 44 list1=['protocol','domain_name','url'] 45 list2=sorted(list1) # 对list1进行排序 46 print(list2) 47 48 d=dict(zip(list1,list2)) #利用zip将两个列表元素按顺序转成字典 49 print(d) 50 #{'protocol': 'domain_name', 'domain_name': 'protocol', 'url': 'url'} 51
a = lambda x:x+1
print (a(3)) 52
# 将列表c输出为字典格式{} d={} c='k1:1|k2:2|k3:3' l=c.split('|') print('l',l) for i in l: print(i) key=i.split(':')[0] value=i.split(':')[1] d[key]=value #循环给key,vlaue赋值 print(d) # {'k1': '1', 'k2': '2', 'k3': '3'}