python學習:字典
1.字典是一系列鍵-值對。每個鍵都與乙個值相關聯,可以通過鍵來訪問相應的值。與鍵相關聯的值可以是數字、字串、列表、字典或者任何的python物件。
2.python不關心字典中鍵-值對的儲存順序,只關心鍵和值之間的關聯關係。也就是不能像列表中一樣通過角標來訪問鍵-值對。
3.使用字典,包括建立字典、訪問字典中的值、新增鍵-值對、修改字典中的值、刪除鍵-值對。
# 建立5個字典,描述某公司員工情況
employee_0 =
employee_1 =
employee_2 =
employee_3 =
employee_4 =
# 建立字典列表
employees =
[employee_0, employee_1, employee_2, employee_3, employee_4]
# 建立空字典,待使用者輸入
employee =
while
true
: employee[
'name']=
input
("please give the empolyee's name: "
)if employee[
'name']==
'':break
employee[
'age']=
input
("please give the empolyee's age: "
)if employee[
'age']==
'':break
employee[
'age']=
int(employee[
'age'])
employee[
'***']=
input
("please give the empolyee's ***: "
)if employee[
'***']==
'':break
employee[
'position']=
input
("please give the empolyee's position: "
)if employee[
'position']==
'':break
employee[
'score']=
input
("please give the empolyee's score: "
)if employee[
'score']==
'':break
employee[
'score']=
int(employee[
'score'])
end_of_input =
input
("do you want to continue? (y/n) "
)if end_of_input.lower()!=
'y':
break
# 按一定格式輸出列表中的字典元素
print
("\nname age *** position score "
)employee_num =
len(employees)
while employee_num:
employee_num -=
1print
( employees[employee_num]
['name']+
" "
+str
(employees[employee_num]
['age'])
+" "
+ employees[employee_num]
['***']+
" "
+ employees[employee_num]
['position']+
" "
+str
(employees[employee_num]
['score'])
+" "
)employee_num =
len(employees)
while employee_num:
employee_num -=
1print
("\nemployee "
+str
(employee_num)
)for key, value in employees[employee_num]
.items():
if key ==
'age'
or key ==
'score'
:print
(key +
": "
+str
(value)
)else
:print
(key +
": "
+ value)
# 輸出列表中包含哪些員工資訊
keys =[''
]employee_num =
len(employees)
while employee_num:
employee_num -=
1for key_temp in employees[employee_num]
.keys():
keys_num =
0for key in keys:
if key_temp != key:
keys_num +=
1if keys_num ==
len(keys)
:keys.pop(0)
print
(keys)
# 找員工中是否有jack
names =
employee_num =
len(employees)
while employee_num:
employee_num -=
1for name in employees[employee_num]
.values():
if name ==
'jack'
:print
(names)
# 列出所有員工評分
scores =
employee_num =
len(employees)
while employee_num:
employee_num -=1[
'score'])
scores.sort(reverse =
true
)score_temp =
0for score in scores:
if score == score_temp:
scores.remove(score)
score_temp = score
print
(scores)
# 把員工按評分順序排列
python學習 字典
字典的形式 形式 dict key 鍵 可以理解為代號 value 值 代號所指代的內容 字典的特點 1 字典是 無序 的,它不能通過偏移來訪問,只能 通過鍵來訪問 2 可以巢狀 3 可變資料型別,可以在原地修改裡面的內容。4 組成字典的 鍵 必須是 不可變 的資料型別,比如,數字,字串,元組等 列...
python學習 字典
這幾天都比較忙,在搞android開發,接著就天天碼 自然就是很晚。抽點時間現在來看一下python方面的基礎,字典。字典 字典是一種可變容器模型,可以為任意型別。字典中由鍵和值組成,中間冒號隔開。使用冒號隔開,這樣就可以一一的建立好乙個物件,物件之間使用逗號隔開。使用arcmap來建立乙個物件。建...
Python學習 字典
有乙個列表和乙個字典 dragonloot gold coin dagger gold coin gold coin ruby inv 寫乙個名為 addtoinventory inventory,addeditems 的函式,其中 inventory 引數是乙個字典,表示玩家的物品清單 像前面專案...