Python系統學習1-7-字典

一、字典

1、概念及內存圖

列表:由一系列變量組成的可變序列容器
字典:由一系列鍵值對組成的可變散列容器
字典優勢:利用(內存)空間,換取(CPU查找)時間
? ? ? ?鍵key? 必須唯一且為不可變數據(字符串,數字,元組),若相同,第二個相同的key覆蓋第一個(通過不可變保證唯一性)
? ? ? 值value 沒有限制

2、基本操作

(1)創建

# 列表善于存儲單一緯度數據
list_name = ["麗麗","紅紅","嘿嘿"]
list_age = [20, 54, 56]
list_sex = ["女", "男", "女"]

# 字典善于存儲多個維度數據
# 創建方法1:字典名 = {鍵1:值1,鍵2:值2}

dict_ll = {"name":"麗麗", "age":"20", "sex":"女"}
dict_hh= {"name":"紅紅", "age":"54", "sex":"男"}
dict_hs = {"name":"嘿嘿", "age":"56", "sex":"女"}

創建方法2:字典名 = dict (容器)

# 需要保質容器的每個元素必須能一分為二

list_name = ["麗麗","紅紅","嘿嘿"]

print(dict(list_name))

(2)添加

添加,其實就是修改(如果key在,就是修改,如果key不在,就是添加)

添加方法:字典名[鍵] = 值

dict_ll = {"name":"麗麗", "age":"20", "sex":"女"}

dict_ll["money"] = 10000

# 定位快,修改

dict_ll["age"] = 26

# 讀取,先判斷,再讀取 print(dict_ll["age"])

注意:dict中根據key找value,直接定位,?字典名[鍵]

? ? ? ? ? ? ? ? ? ? ?根據value找key,則需要一一遍歷

(3)刪除

del 字典名[鍵1],字典名[鍵2]? 刪除后鍵值對同步消失

(4)遍歷
dict_ll = {"name":"麗麗", "age":"20", "sex":"女"}
# 所有key
for key in dict_ll:print(key)
'''
name
age
sex
'''
# 所有key
for key in dict_ll.keys():print(key)
'''
name
age
sex
'''# 所有value
for value in dict_ll.values():print(value)
'''
麗麗
20
女
'''
# 所有鍵和值
for item in dict_ll.items():print(item)
'''
('name', '麗麗')
('age', '20')
('sex', '女')
'''
# 等價于
for key,value in dict_ll.items():  # 上述的拆包print(key,value)
'''
name 麗麗
age 20
sex 女
'''
# 默認打印只有key值
print(dict_ll) #['name', 'age', 'sex']
print(dict_LL.items())

3、列表list和字典dict互相轉換

dict_ll = {"name":"麗麗", "age":"20", "sex":"女"}
# dict轉list
print(list(dict_ll.items()))
# [('name', '麗麗'), ('age', '20'), ('sex', '女')]
# list轉dict
print(dict([('name', '麗麗'), ('age', '20'), ('sex', '女')]))
# {'name': '麗麗', 'age': '20', 'sex': '女'

4、練習

# 疫情信息
list_epidemic = [{"region": "臺灣", "new": 16,"now": 2339, "total": 16931,},{"region": "陜西", "new": 182,"now": 859, "total": 1573,},{"region": "浙江", "new": 2,"now": 505, "total": 2008,},
]
# --打印所有疫情信息
for i in range(len(list_epidemic)):print(list_epidemic[i]["region"])print(list_epidemic[i]["new"])# 優化
for item in list_epidemic:print(item["region"])print(item["new"])# --查找新增人數大于10的地區名稱(將結果存入新列表)
new_list = []
for i in range(len(list_epidemic)):if list_epidemic[i]["new"]>10:new_list.append(list_epidemic[i]["region"])
print(new_list)# 優化
new_list = []
for item in list_epidemic:if item["new"] > 10:new_list.append(item["new"])
# --查找現有人數最大的地區信息(結果為字典)
max = list_epidemic[0]["now"]
flag = 0
for i in range(0,len(list_epidemic)):if max <= list_epidemic[i]["now"]:max = list_epidemic[i]["now"]flag = i
print(list_epidemic[flag])
list_epidemic = [{"region": "臺灣", "new": 16,"now": 2339, "total": 16931,},{"region": "陜西", "new": 182,"now": 859, "total": 1573,},{"region": "浙江", "new": 2,"now": 505, "total": 2008,},
]
# --根據現有人數對疫情信息降序(大->小)排列
for i in range(len(list_epidemic)):for j in range(i+1,len(list_epidemic)):if list_epidemic[i]["now"] < list_epidemic[j]["now"]:list_epidemic[i],list_epidemic[j]=list_epidemic[j],list_epidemic[i]

二、容器小結

1、種類與特征

????????字符串:存儲字符編碼(a-97),不可變,序列

????????列表list:存儲變量(地址),可變,序列

????????元組tuple:存儲變量(地址),不可變,序列

????????字典dict:存儲鍵值對,可變,散列

# 字典想拿到第一個鍵值對  轉換為列表/元組
dict_ll = {"name":"麗麗", "age":"20", "sex":"女"}
list_key = list(dict_ll())  # 拿到的只有鍵
print(list_key)
key = list_key[0]
value = dict_ll[key]list_item = list(dict_ll.items())
print(list_item[0])# 轉成元組更好,省內存
tuple_item = tuple(dict_ll.items())
print(tuple_item[0])

2、Python語言有哪些數據類型

????????可變類型:預留空間+自動擴容
??? ????????如:列表list,字典dict
??? ????????優點:操作數據方便(能夠增刪改)
??? ????????缺點:占用內存太大
? ? ? ? 不可變類型:按需分配
??? ????????如:int,float,bool,str,tuple
??? ????????優點:占用內存小
??? ????????缺點:不能適應現實的變化

3、序列與散列

????????序列:支持索引切片,定位數據靈活
????????散列:通過鍵定位數據,速度最快

4、語法

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?列表? ? ? ? ? ? ? ? ? ? ? ? ? ? ?字典
?? 創建
??????? 列表名=[數據1,數據2]? ? ? ? ? ? ? ? ? ? 字典名={鍵1:值1,鍵2:值2}
??????? 列表名=list(容器)? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 字典名=dict(容器)
?? 添加
??????? 列表名.append(元素)? ? ? ? ? ? ? ? ? ? ? ? 字典名[鍵]=值? 不可變數據才可以當鍵
??????? 列表名.insert(索引,元素)
?? 定位
??????? 列表名[整數]? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 字典名[鍵]
??????? 列表名[開始:結束:間隔]
?? 刪除
???????? del 列表名[索引或切片]? ? ? ? ? ? ? ? ? ? del 字典名[鍵] ,鍵值都刪除
???????????????? 注意索引越界
???????? 列表名.remove(數據)
???????????????? 注意數據必須存在于列表中
?? 遍歷
??????? for item in 列表名:? ? ? ? ? ? ? ? ? ? ? ? ? ? for key in 字典:
??????? for i range(len(列表名)):? ? ? ? ? ? ? ? ? ?for value in 字典.values():
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?for k,v in 字典.items():?

三、練習1

# 2. 在終端中獲取顏色(RGBA),打印描述信息,
#     否則提示顏色不存在
#     "R" -> "紅色"
#     "G" -> "綠色"
#     "B" -> "藍色"
#     "A" -> "透明度"
dict_rgb = {"R":"紅色", "G":"綠色", "B":"藍色", "A":"透明度"}
input_rgb = input("請輸入顏色:")
if input_rgb in dict_rgb:print(dict_rgb[input_rgb])
else:print("不存在")# 3. 將列表中的數字累減
list02 = [5, 1, 4, 6, 7, 4, 6, 8, 5]
sum_last = list02[0]
for i in range(1, len(list02)):sum_last -= list02[i]
print(sum_last)# 4. 在列表中查找最大值(不使用max,自定義算法實現)
#     思路:
#         假設第一個元素就是最大值
#         依次與后面元素進行比較
# #         如果發現更大值,則替換
list02 = [5, 1, 4, 6, 7, 4, 6, 8, 5]
max = list02[0]
for item in list02:if max < item:max = item
print(max)# 5. (選做)彩票:雙色球
#     紅色:6個  1--33之間的整數   不能重復
#     藍色:1個  1--16之間的整數
#     1) 隨機產生一注彩票(列表(前六個是紅色,最后一個藍色))
#     2) 在終端中錄入一支彩票
#     要求:滿足彩票的規則.
import random
list_lottery = []
for i in range(6):num = random.randint(1,33)while num in list_lottery:num = random.randint(1, 33)list_lottery.append(num)
list_lottery.append(random.randint(1,16))# 優化
import random
list_lottery = []
while len(list_lottery) < 6:num = random.randint(1, 33)if num not in list_lottery:list_lottery.append(num)
list_lottery.append(random.randint(1,16))# 2) 在終端中錄入一支彩票
#     要求:滿足彩票的規則.
list_lottery = []
i = 1
while i <= 6:num = int(input(f"請錄入紅色第{i}注彩票:"))if 1 < num < 33:if num not in list_lottery:list_lottery.append(num)i += 1else:print("不能重復,請重新輸入")else:print("您輸入的數字超出范圍1-33,請重新輸入")while True:num2 = int(input(f"請錄入藍色第{i}注彩票:"))if 1 < num2 < 6:list_lottery.append(num2)breakelse:print("您輸入的數字超出范圍1-6,請重新輸入")
print(f"下注為{list_lottery}")

四、練習二

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/37991.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/37991.shtml
英文地址,請注明出處:http://en.pswp.cn/news/37991.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

hbase 報錯 Master passed us a different hostname to use; was=

原因 wsl2的 /etc/hosts 配置的不兼容,我這里是ubuntu22 命令行輸入hostname 看輸出什么,比如輸出 aaa 那么替換/etc/hosts 127.0.0.1 aaa

vb+sql醫院門診管理系統設計與系統

摘要 信息時代已經來臨,計算機應用于醫院的日常管理,為醫院的現代化帶來了從未有過的動力和機遇,為醫療衛生領域的發展提供了無限的潛力。采用計算機管理信息系統已成為醫院管理科學化和現代化的標志,給醫院帶來了明顯的經濟效益和社會效益。 本文介紹了數據庫管理系統的…

每天一個知識點——L2R

面試的時候&#xff0c;雖然做過醫療文獻搜索&#xff0c;也應用過L2R的相關模型&#xff0c;但涉及到其中的一些技術細節&#xff0c;都會成為我拿不下offer永遠的痛。也嘗試過去理解去背下一些知識點&#xff0c;終究沒有力透紙背&#xff0c;隨著時間又開始變得模糊&#xf…

海量數據遷移,亞馬遜云科技云數據庫服務為大庫治理提供新思路

1.背景 目前&#xff0c;文檔型數據庫由于靈活的schema和接近關系型數據庫的訪問特點&#xff0c;被廣泛應用&#xff0c;尤其是游戲、互聯網金融等行業的客戶使用MongoDB構建了大量應用程序&#xff0c;比如游戲客戶用來處理玩家的屬性信息&#xff1b;又如股票APP用來存儲與時…

Stable Diffusion - 幻想 (Fantasy) 風格與糖果世界 (Candy Land) 人物提示詞配置

歡迎關注我的CSDN&#xff1a;https://spike.blog.csdn.net/ 本文地址&#xff1a;https://spike.blog.csdn.net/article/details/132212193 圖像由 DreamShaper8 模型生成&#xff0c;融合糖果世界。 幻想 (Fantasy) 風格圖像是一種以想象力為主導的藝術形式&#xff0c;創造了…

27.Netty源碼之FastThreadLocal

highlight: arduino-light FastThreadLocal FastThreadLocal 的實現與 ThreadLocal 非常類似&#xff0c;Netty 為 FastThreadLocal 量身打造了 FastThreadLocalThread 和 InternalThreadLocalMap 兩個重要的類。下面我們看下這兩個類是如何實現的。 FastThreadLocalThread 是對…

【論文閱讀】NoDoze:使用自動來源分類對抗威脅警報疲勞(NDSS-2019)

NODOZE: Combatting Threat Alert Fatigue with Automated Provenance Triage 伊利諾伊大學芝加哥分校 Hassan W U, Guo S, Li D, et al. Nodoze: Combatting threat alert fatigue with automated provenance triage[C]//network and distributed systems security symposium.…

uniapp安卓ios打包上線注意事項

1、安卓包注意事項 隱私政策彈框提示 登錄頁面隱私政策默認不勾選隱私政策同意前不能獲取用戶權限APP啟動時&#xff0c;在用戶授權同意隱私政策前&#xff0c;APP及SDK不可以提前收集和使用IME1、OAID、IMS1、MAC、應用列表等信息 ios包注意事項 需要有注銷賬號的功能 3、安…

前后端分離------后端創建筆記(05)用戶列表查詢接口(上)

本文章轉載于【SpringBootVue】全網最簡單但實用的前后端分離項目實戰筆記 - 前端_大菜007的博客-CSDN博客 僅用于學習和討論&#xff0c;如有侵權請聯系 源碼&#xff1a;https://gitee.com/green_vegetables/x-admin-project.git 素材&#xff1a;https://pan.baidu.com/s/…

vue3中簡單快速的做個表單輸入框驗證

<el-form ref"formRef" :model"processingProgressForm"><el-form-item label"服務商名稱:" :label-width"120" prop"rejectRemarks" :rules"[{ required: true, message: 服務商名稱不能為空 }]">&l…

通過網關訪問微服務,一次正常,一次不正常 (nacos配置的永久實例卻未啟動導致)

微服務直接訪問沒問題&#xff0c;通過網關訪問&#xff0c;就一次正常訪問&#xff0c;一次401錯誤&#xff0c;交替正常和出錯 負載均衡試了 路由配置檢查了 最后發現nacos下竟然有2個order服務實例&#xff0c;我明明只開啟了一個呀 原來之前的8080端口微服務還殘留&…

基于架構的軟件開發方法

基于架構的軟件開發方法 基于架構的軟件開發方法是由架構驅動的&#xff0c;即指由構成體系結構的商業、質量和功能需求的組合驅動的。使用ABSD 方法&#xff0c;設計活動可以從項目總體功能框架明確就開始&#xff0c;這意味著需求抽取和分析還沒有完成(甚至遠遠沒有完成)&am…

純C#使用Visionpro工具2 操作斑點工具

結果圖 通過斑點工具中非圓性找取圓特征 代碼 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.For…

ApacheCon - 云原生大數據上的 Apache 項目實踐

Apache 軟件基金會的官方全球系列大會 CommunityOverCode Asia&#xff08;原 ApacheCon Asia&#xff09;首次中國線下峰會將于 2023 年 8 月 18-20 日在北京麗亭華苑酒店舉辦&#xff0c;大會含 17 個論壇方向、上百個前沿議題。 字節跳動云原生計算團隊在此次 CommunityOve…

OpenSSL 遠程升級到 3.2.1

OpenSSL 遠程升級到 3.2.1 文章目錄 OpenSSL 遠程升級到 3.2.1背景升級 OpenSSL1. 查看 OpenSSL版本2. 下載最新穩定版本 OpenSSL3. 解壓縮&#xff0c;安裝4. 配置 背景 最近的護網行動&#xff0c;被查出來了好幾個關于OpenSSH的漏洞。需要升級OpenSSH&#xff0c;升級OpenS…

冠達管理:價格破發是什么意思啊?

價格破發是股票商場中一個比較常見的術語&#xff0c;也是常常讓出資者感到困惑的現象之一。價格破發是指新股發行后&#xff0c;由于各種原因&#xff0c;股票價格低于發行價的現象。那么&#xff0c;價格破發的原因是什么呢&#xff1f;價格破發與出資者有哪些聯系呢&#xf…

C和指針(一)

C和指針&#xff08;一&#xff09; 預處理指令main 函數常量及變量整型字面值指針&#xff1a;基本聲明&#xff1a;隱式聲明&#xff1a;常量&#xff1a; 預處理指令 預處理器用庫函數頭文件的內容替換掉相對應的#include指令語句。 使用stdio.h頭文件可以使我們訪問標準I/…

企業直播MR虛擬直播(MR混合現實直播技術)視頻介紹

到底什么是企業直播MR虛擬直播&#xff08;MR混合現實直播技術&#xff09;&#xff1f; 企業直播MR虛擬直播新玩法&#xff08;MR混合現實直播技術&#xff09; 我的文章推薦&#xff1a; [視頻圖文] 線上研討會是什么&#xff0c;企業對內對外培訓可以用線上研討會嗎&#x…

24屆近5年南京工業大學自動化考研院校分析

今天給大家帶來的是南京工業大學控制考研分析 滿滿干貨&#xff5e;還不快快點贊收藏 一、南京工業大學 學校簡介 南京工業大學&#xff08;Nanjing Tech University&#xff09;&#xff0c;簡稱“南工”&#xff0c;位于江蘇省南京市&#xff0c;由國家國防科技工業局、住…