python 字典所有操作

2022-09-07 18:51:22 字數 2506 閱讀 8315

# 字典的建立

# dict1 = {}

# print(type(dict1))

## dict2 =

# print(dict2)

## dict3 = dict(name = 'eric',age = 28)

# print(dict3)

# 取值操作

# employee =

# name = employee['name']

# print(name)

## *** = employee.get('***')

# print(***)

## dept = employee.get('dept','其他部門')

# print(dept)

# in 成員運算子 判斷 key 是否存在

# print('name' in employee) # true

# print('dept' in employee) # false

# print('dept' not in employee) # true

# 遍歷字典

# 汪峰

# 男# 1997-10-20

# for key in employee:

# v = employee[key]

# print(v)

# name 汪峰

# *** 男

# hiredate 1997-10-20

# for k,v in employee.items():

# print(k,v)

# 單個更新

# employee['grade'] = 'b'

# print(employee)

# # 多個更新

# employee.update(salary = 1200, welfare = 150)

# print(employee)

## # 新增

# employee['dept'] = '研發部'

# print(employee)

## # 刪除操作

# employee.pop('dept')

# print(employee)

# # 刪除操作 刪除最後乙個 kv

# employee.popitem()

# print(employee)

## # 清空字典

# employee.clear()

# print(employee)

# emp1 =

# emp2 =

## # setdefault 設定預設值 存在就忽略 不存在就建立

# emp2.setdefault('grade','c')

# print(emp2)

# 獲取字典的檢視

# k = emp1.keys()

# # dict_keys(['name', 'grade'])

# print(k)

## v = emp1.values()

# # dict_values(['jacky', 'b'])

# print(v)

## items = emp1.items()

# # dict_items([('name', 'jacky'), ('grade', 'b')])

# print(items)

# 格式化字串

# emp_str = "姓名:,評級:,入職時間".format_map(emp1)

# print(emp_str)

# 雜湊值

# h1 = hash("dabc")

# # print(h1)

# # h2 = hash("1231231")

# # print(h2)

# 例子

source = "12345,jace,ercd,php,5000$2345,clead,ercd,dfd,5000$22345,clead,ercd,dfd,5000$32345,clead,ercd,dfd,5000"

employee_list = source.split("$")

print(employee_list)

all_emp = {}

for i in range(0,len(employee_list)):

# print(i)

e = employee_list[i].split(",")

# print(e)

employee =

print(employee)

all_emp[employee['no']] = employee

print(all_emp)

empno = input('編號:')

if empno in all_emp:

emp = all_emp.get(empno)

print(emp);

else:

print('編號不存在')

python操作字典 Python 字典操作高階

學習了 python 基本的字典操作後,學習這些高階操作,讓寫出的 更加優雅簡潔和 pythonic 與字典值有關的計算 問題想對字典的值進行相關計算,例如找出字典裡對應值最大 最小 的項。解決方案一 假設要從字典 中找出值最小的項,可以這樣做 d min zip d.values d.keys 2...

python 字典操作

python 語法之字典 2009 10 21 磁針石 xurongzhong gmail.com 部落格 oychw.cublog.cn python essential reference 4th edition 2009 beginning python from novice to prof...

python 字典操作

1 什麼是字典?字典是python語言中唯一的對映型別。對映型別物件裡雜湊值 鍵,key 和指向的物件 值,value 是一對多的的關係,通常被認為是可變的雜湊表。字典物件是可變的,它是乙個容器型別,能儲存任意個數的python物件,其中也可包括其他容器型別。字典型別與序列型別的區別 1.訪問和訪問...