#字典是列表型数据结构,元素用“键-值”方式配对存储,定义时放{ }里 字典中键不可以重复,值可以重复
print("1:定义字典")
fruits = {'西瓜':15,'香蕉':20,'水蜜桃':25}
noodles = {'牛肉面':100,'肉丝面':100,'阳春面':60}
print(fruits,noodles,sep="---")
print(type(fruits))print("\n\n2:获取字典的值")
print("水蜜桃一斤 = ",fruits['水蜜桃'],"元")print("\n\n3:增加字典元素")
fruits['橘子'] = 10
print(fruits)
print("橘子一斤 = ",fruits['橘子'],"元")print("\n\n4:更改字典的值")
print("旧橘子一斤 = ",fruits['橘子'],"元")
fruits['橘子'] = 20
print("新橘子一斤 = ",fruits['橘子'],"元")print("\n\n5:删除字典的特定元素")
print("旧fruits字典元素 = ",fruits)
del fruits['橘子']
print("新fruits字典元素 = ",fruits)print("\n\n6:删除字典的所有元素") #即空字典
print("旧fruits字典元素 = ",fruits)
fruits.clear()
print("新fruits字典元素 = ",fruits)print("\n\n7:建立空字典")
zero={}
print("zero字典元素 = ",zero)print("\n\n8:字典的复制")
cfruits = fruits.copy()
print("地址 = ",id(fruits),"fruits元素 = ",fruits)
print("地址 = ",id(cfruits),"fruits元素 = ",cfruits)print("\n\n9:取得字典元素数量")
print("fruits字典元素的数量 = ",len(fruits))print("\n\n10:验证元素是否存在")
key = input ("请输入key = ")
value = input("请输入value = ")
if key in fruits:print("%s已经在字典中" % key)
else:fruits[key] = valueprint("新fruits字典元素 = ",fruits)print("\n\n11:遍历字典")
players = {'1':'team5', #字典元素内容过长,可以分行'2':'team4','3':'team3','4':'team2','5':'team1'}
for name,team in players.items( ): #items()遍历函数print("\nname:",name)print("team:",team)print("\n\n12:遍历字典的key")
for name in players.keys():print("name: ",name)print("\n\n13:遍历字典的value")
for team in players.values():print(team)print("\n\n14:遍历排序字典") #sorted()
for name in sorted(players.keys()):print(name)print("\n\n15:建立字典列表")
armys = [] #空列表
for soldier_number in range(50):soldier = {'tag':'red','score':3,'speed':'slow'}armys.append(soldier) #重点!!
print("打印前3个小兵的资料")
for soldier in armys[:3]:print(soldier)
for soldier in armys[35:38]:if soldier['tag'] =='red':soldier['tag'] ='blue'soldier['score'] ='5'soldier['speed'] ='medium'
print("打印35-40小兵的资料")
for soldier in armys[34:40]:print(soldier)print("\n\n16:遍历含有列表元素的字典")
sports = {'1':['a','aa','aaa'],'2':['b','bb','bbb'],'3':['c','cc','ccc']}
for name,favorite_sports in sports.items():print("%s 喜欢的运动是:" % name)for sport in favorite_sports:print(" ",sport)print("\n\n17:遍历含有字典元素的字典")
wechat_account = {'111':{'last_name':'zhao','first_name':'fugui','city':'shanxi'},'222':{'last_name':'pan','first_name':'meili','city':'guilin'}}
for account,account_info in wechat_account.items():print("使用者账号 = ",account)name = account_info['last_name'] + " " + account_info['first_name']print("name =",name)print("city =",account_info['city'])print("\n\n18:while在字典的应用")
survey_diet = {}
market_survey = True
while market_survey:name = input("\n请输入姓名 :")travel_location = input("梦幻旅游景点")survey_diet[name] = travel_location #将输入存入字典repeat = input("是否有人要参加市场调查?(x/y)")if repeat != 'y':market_survey = False
print("\n\n以下是市场调查的结果")
for user,location in survey_diet.items():print(user,"梦幻旅游景点",location)print("\n\n19:常用字典函数--len()")
wechat_account = {'111':{'last_name':'zhao','first_name':'fugui','city':'shanxi'},'222':{'last_name':'pan','first_name':'meili','city':'guilin'}}print("wechat_account字典元素个数",len(wechat_account))
print("wechat_account['111']元素个数",len(wechat_account['111']))
print("wechat_account['222']元素个数",len(wechat_account['222']))print("\n\n20:常用字典函数--fromkeys()") #name_dict = dict.fromkeys(seq,value) seq序列:字典的键 value:值
#列表转成字典
seq1 = {'name','city'} #定义列表
list_dict1 = dict.fromkeys(seq1)
print("字典1",list_dict1)
list_dict2 = dict.fromkeys(seq1,'1')
print("字典2",list_dict2)
tup_dict1 = dict.fromkeys(seq1)
print("字典3",tup_dict1)
tup_dict2 = dict.fromkeys(seq1,'1')
print("字典4",tup_dict2)print("\n\n21:常用字典函数--get()") # 返回键的值,若不存在返回默认值(none).get 不会改变字典内容
study = {'a':1,'b':2,'c':3}
print("value = ",study.get('a'))
print("value = ",study.get('d'))
print("value = ",study.get('d',10))print("\n\n22:常用字典函数-setdefault()") # 与get类似,若搜寻的键不在字典内,,则会将键-值添加到字典
study.setdefault('d')
print("增加d",study)
study.setdefault('e',5)
print("增加d",study)print("\n\n23:常用字典函数-pop") #pop() 删除元素
dell = study.pop('e')
print("被删除的值 : ",dell)
print("删除后的字典: ",study)print("\n\n24:删除字典")
del fruits
本文是作者学习洪锦魁老师的《Python王者归来》过程的代码