字典的進階操作[00000000]巢狀迴圈
阿新 • • 發佈:2022-05-16
# # 字典的進階操作,迴圈和巢狀 # dic = {"key0": "v0", # "key1": "v1", # "key2": "v2", # "key3": "v3", # "key4": "v4", # "key5": "v5", # } # # print(dic) # # 1.可以用for迴圈,直接拿到key # # for key in dic: # # print(key, dic[key]) # 拿出key,與value # # # 2.希望把所有的key儲存在列表中 # # print(list(dic.keys())) # 拿到所有的key# # # list(dic.keys()) 把所有的key放入列表中 # # # 3.希望把所有的value值放入一個列表中 # # print(list(dic.values())) # 拿到所有的value值 # # 4.直接拿到字典的key和value # # print(type(dic.items())) # # t = {1: "a", 2: "b", 77: "b", 4: "d"} # # print(type(t[77])) # # for a in t: # # # print(t[77]) # # a, b = [1, 2] # 元組或者列表都可以執行改操作,該操作被稱為解包(解構)# # # ValueError: too many values to unpack (expected 2) # # print(a) # # print(b) # # for item in dic.items(): # for key, value in dic.items(): # 可以直接拿到字典的所有key和value值 # # 程式可以簡化為替換item變數 # # print(item) # 確定item中只有兩項元素 # # key, value = item # print(key, value) # print(type(value))# 5.字典的巢狀(鍵值只有一個,固定的,值value可以巢狀 wangfeng = { "name": "汪峰", "age": 48, "wife": { "name": "章子怡", "age": 38, "assistant": { "name": "大熊", "age": 29 } } } # 我需要汪峰的老婆的助手的年齡 age = wangfeng['wife']['assistant']['name'] print(age) # 給汪峰的老婆的助手加一歲 wangfeng['wife']['assistant']['age'] = wangfeng['wife']['assistant']['age'] + 1 print(wangfeng)