python基礎——字典綜合練習
1.輸出字典內陣列平均值
a={'name':'Tom','age':20,'address':'北京','score':[89,99,78,95]}
a = {'name': 'Tom', 'age': 20, 'address': '北京', 'score': [89, 99, 78, 95]}
b = a['score'] # 找出'score'對應的值,定義為b
sum = 0
for i in b: # 用for迴圈求出和
sum += i
print(sum / len(b)) # 用和除以列表長度
輸出結果: 90.25
2.輸出字典003的所有key,value
a={'001':{'name':'張三','age':20,'address':'北京','score':88},
'002':{'name':'李四','age':20,'address':'北京','score':78},
'003':{'name':'王五','age':20,'address':'北京','score':95},
'004':{'name':'小明','age':20,'address':'北京','score':90}}
a={'001':{'name':'張三','age':20,'address':'北京','score':88}, '002':{'name':'李四','age':20,'address':'北京','score':78}, '003':{'name':'王五','age':20,'address':'北京','score':95}, '004':{'name':'小明','age':20,'address':'北京','score':90}} b = a['003'] # 找到'003'所對應的字典 for key,value in b.items(): # b.items()是列表套元組的形式 print(key,'-----',value)
輸出結果:name ----- 王五
age ----- 20
address ----- 北京
score ----- 95
3.給所有北京人加100000住房補貼
a={'001':{'name':'張三','age':20,'address':'北京','score':88},
'002':{'name':'李四','age':20,'address':'山東','score':78},
'003':{'name':'王五','age':20,'address':'北京','score':95},
'004':{'name':'小明','age':20,'address':'河北','score':90}
a = {'001': {'name': '張三', 'age': 20, 'address': '北京', 'score': 88},
'002': {'name': '李四', 'age': 20, 'address': '山東', 'score': 78},
'003': {'name': '王五', 'age': 20, 'address': '北京', 'score': 95},
'004': {'name': '小明', 'age': 20, 'address': '河北', 'score': 90}}
for i in a.values():
if i['address'] == '北京': # 判斷出那些字典中有北京
i['housing add'] = 10000 # 向有北京的字典中加入
print(i)
輸出結果:
{'name': '張三', 'age': 20, 'address': '北京', 'score': 88, 'housing add': 10000}
{'name': '李四', 'age': 20, 'address': '山東', 'score': 78}
{'name': '王五', 'age': 20, 'address': '北京', 'score': 95, 'housing add': 10000}
{'name': '小明', 'age': 20, 'address': '河北', 'score': 90}
4.輸出二維字典最大age和最小age
a={ '001':{'name':"李四",'age':28,'address':"山東",'score':88},
'002':{'name':"張三",'age':18,'address':"北京",'score':98},
'003':{'name':"小明",'age':48,'address':"河北",'score':90},
'004':{'name':"王五",'age':38,'address':"北京",'score':78}
}
a = {'001': {'name': "李四", 'age': 28, 'address': "山東", 'score': 88},
'002': {'name': "張三", 'age': 18, 'address': "北京", 'score': 98},
'003': {'name': "小明", 'age': 48, 'address': "河北", 'score': 90},
'004': {'name': "王五", 'age': 38, 'address': "北京", 'score': 78}
}
max = a['001']['age'] # 定義第一個鍵值對是最大和最小的。
min = a['001']['age']
for i in a.values():
if i['age'] > max: # 將每個找到的的值與max和min比較
max = i['age']
elif i['age'] < min:
min = i['age']
print('max:{}\nmin:{}'.format(max, min))
輸出結果: max:48
min:18