正確的詞典訪問方式

unity3d 詞典訪問

Python字典指南 (Python Dictionary Guide)

The dictionary is one of the data structures that are ready to use when programming in Python.

字典是使用Python進行編程時可以使用的數據結構之一。

在我們開始之前,什么是字典? (Before We Start, What is a Dictionary?)

Dictionary is an unordered and unordered Python collection that maps unique keys to some values. In Python, dictionaries are written by using curly brackets {} . The key is separated from the key by a colon : and every key-value pair is separated by a comma ,. Here’s how dictionaries are declared in Python.

字典是一個無序且無序的Python集合,它將唯一鍵映射到某些值。 在Python中,字典使用大括號{}編寫。 的密鑰是從一個冒號鍵分離:與每一個鍵-值對由逗號分隔, 。 這是在Python中聲明字典的方式。

#A dictionary containing basketball players with their heights in m
playersHeight = {"Lebron James": 2.06,
"Kevin Durant": 2.08,
"Luka Doncic": 2.01,
"James Harden": 1.96}

We have created the dictionary, however, what’s good about it if we cannot retrieve the data again right? This is where a lot of people do it wrong. I should admit, I was among them not long ago. After I realize the advantage, I never turn back even once. That’s why I am motivated to share it with you guys.

我們已經創建了字典,但是,如果我們不能再次正確檢索數據,那有什么用呢? 這是很多人做錯事的地方。 我應該承認,不久前我就是其中之一。 意識到優勢之后,我再也不會回頭一次。 這就是為什么我有動力與大家分享。

錯誤的方法 (The Wrong Way)

The well-known, or I should say the traditional way to access a value in a dictionary is by referring to its key name, inside a square bracket.

眾所周知,或者我應該說在字典中訪問值的傳統方法是在方括號內引用其鍵名。

print(playersHeight["Lebron James"]) #print 2.06
print(playersHeight["Kevin Durant"]) #print 2.08
print(playersHeight["Luka Doncic"]) #print 2.01
print(playersHeight["James Harden"]) #print 1.96

Everything seems OK, right? Not so fast! What do you think will happen if you type a basketball player’s name that is not in the dictionary? Look closely

一切似乎還好吧? 沒那么快! 如果您鍵入詞典中沒有的籃球運動員的名字,您會怎么辦? 仔細看

playersHeight["Kyrie Irving"] #KeyError 'Kyrie Irving'

Notice that when you want to access the value of the key that doesn’t exist in the dictionary will result in a KeyError. This could quickly escalate into a major problem, especially when you are building a huge project. Fret not! There are certainly one or two ways to go around this.

請注意,當您要訪問字典中不存在的鍵的值時,將導致KeyError。 這可能很快會升級為一個主要問題,尤其是在構建大型項目時。 不用擔心! 解決這個問題肯定有一兩種方法。

Using If

使用If

if "Kyrie Irving" is in playersHeight:
print(playersHeight["Kyrie Irving"])

Using Try-Except

使用Try-Except

try:
print("Kyrie Irving")
except KeyError as message:
print(message) #'Kyrie Irving'

Both snippets will run with no problem. For now, it seems okay, we can tolerate writing more lines to deal with the possibility of KeyError. Nevertheless, it will become annoying when the code you are writing is wrong.

兩個片段都可以正常運行。 就目前而言,似乎還可以,我們可以忍受寫更多的行來解決KeyError的可能性。 但是,當您編寫的代碼錯誤時,它將變得很煩人。

Luckily, there are better ways to do it. Not one, but two better ways! Buckle up your seat and get ready!

幸運的是,有更好的方法可以做到這一點。 不是一種,而是兩種更好的方法! 系好安全帶,準備好!

正確的方式 (The Right Way)

Using get() Method

使用get()方法

Using the get method is one of the best choices you can make when dealing with a dictionary. This method has 2 parameters, the first 1 is required while the second one is optional. However, to use the full potential of the get() method, I suggest you fill both parameters.

使用get方法是處理字典時最好的選擇之一。 此方法有2個參數,第一個參數是必需的,第二個參數是可選的。 但是,要充分利用get()方法的潛力,建議您同時填寫兩個參數。

  • First: the name of the key which value you want to retrieve

    第一:密鑰名稱要檢索的值
  • Second: the value used if the key we are searching does not exist in the

    第二:如果要搜索的鍵不存在,則使用該值
#A dictionary containing basketball players with their heights in m
playersHeight = {"Lebron James": 2.06,
"Kevin Durant": 2.08,
"Luka Doncic": 2.01,
"James Harden": 1.96}#If the key exists
print(playersHeight.get("Lebron James", 0)) #print 2.06
print(playersHeight.get("Kevin Durant", 0)) #print 2.08#If the key does not exist
print(playersHeight.get("Kyrie Irving", 0)) #print 0
print(playersHeight.get("Trae Young", 0)) #print 0

When the key exists, get() method works exactly the same to referencing the name of the key in a square bracket. But, when the key does not exist, using get() method will print the default value we enter as the second argument.

當鍵存在時, get()方法的工作原理與在方括號中引用鍵的名稱完全相同。 但是,當鍵不存在時,使用get()方法將打印我們輸入的默認值作為第二個參數。

If you don’t specify the second value, a None value will be returned.

如果您未指定第二個值,則將返回None值。

You should also note that using the get() method will not modify the original dictionary. We will discuss it further later in this article.

您還應該注意,使用get()方法不會修改原始字典。 我們將在本文后面進一步討論。

Using setdefault() method

使用setdefault()方法

What? There is another way? Yes of course!

什么? 還有另一種方法嗎? 當然是!

You can use setdefault() method when you not only want to skip the try-except step but also overwrite the original dictionary.

當您不僅要跳過try-except步驟而且要覆蓋原始字典時,可以使用setdefault()方法。

#A dictionary containing basketball players with their heights in m
playersHeight = {"Lebron James": 2.06,
"Kevin Durant": 2.08,
"Luka Doncic": 2.01,
"James Harden": 1.96}#If the key exists
print(playersHeight.setdefault("Lebron James", 0)) #print 2.06
print(playersHeight.setdefault("Kevin Durant", 0)) #print 2.08#If the key does not exist
print(playersHeight.setdefault("Kyrie Irving", 0)) #print 0
print(playersHeight.setdefault("Trae Young", 0)) #print 0

What I mean by overwriting is this, when you see the original dictionary again, you will see this.

我的意思是重寫,當您再次看到原始詞典時,您將看到此。

print(playersHeight)
"""
print
{"Lebron James": 2.06,
"Kevin Durant": 2.08,
"Luka Doncic": 2.01,
"James Harden": 1.96,
"Kyrie Irving": 0,
"Trae Young": 0}

Other than this feature, the setdefault() method is exactly similar to the get() method.

除了此功能外, setdefault()方法與get()方法完全相似。

最后的想法 (Final Thoughts)

Both get() and setdefault() are advanced techniques that you all must familiarize with. Implementing it is not hard and straightforward. The only barrier for you now is to break those old habits.

get()setdefault()都是您都必須熟悉的高級技術。 實施它并不困難和直接。 現在,您的唯一障礙是打破這些舊習慣。

However, I believe that as you use it, you will experience the difference immediately. After a while, you will no longer hesitate to change and start using get() and setdefault() methods.

但是,我相信,當您使用它時,您會立即體驗到不同之處。 一段時間后,您將不再需要更改并開始使用get()setdefault()方法。

Remember, when you don’t want to overwrite the original dictionary, go with get() method.

請記住,當您不想覆蓋原始字典時,請使用get()方法。

When you want to make changes to the original dictionary, setdefault() will be the better choice for you.

當您想更改原始字典時, setdefault()將是您的更好選擇。

Regards,

問候,

Radian Krisno

拉迪安·克里斯諾(Radian Krisno)

翻譯自: https://towardsdatascience.com/the-right-way-to-access-a-dictionary-7a19b064e62b

unity3d 詞典訪問

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

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

相關文章

Vue.js(5)- 全局組件

全局組件 定義組件的語法 Vue.component(組件的名稱, { 組件的配置對象 }) 在組件的配置對象中:可以使用 template 屬性指定當前組件要渲染的模板結構; 使用組件的語法 把 組件的名稱, 以標簽的形式,引入到頁面上就行; // 導入v…

DNS的幾個基本概念:

一. 根域 就是所謂的“.”,其實我們的網址www.baidu.com在配置當中應該是www.baidu.com.(最后有一點),一般我們在瀏覽器里輸入時會省略后面的點,而這也已經成為了習慣。 根域服務器我們知道有13臺&#xff…

廢水處理計算書 excel_廢水監測數據是匿名的嗎?

廢水處理計算書 excelOur collective flushes help track and respond to Covid-19 and so much more. Your body waste contains harvestable compounds that can reveal your illnesses and diseases, consumption habits, and cosmetic use. Researchers gain insights from…

文件在線預覽 圖片 PDF Excel Word

1、前端實現pdf文件在線預覽功能 方式一、pdf文件理論上可以在瀏覽器直接打開預覽但是需要打開新頁面。在僅僅是預覽pdf文件且UI要求不高的情況下可以直接通過a標簽href屬性實現預覽 <a href"文檔地址"></a> 2、word、xls、ppt文件在線預覽功能 word、pp…

數據科學還是計算機科學_您應該擁有數據科學博客的3個原因

數據科學還是計算機科學“Start a Blog to cement the things you learn. When you teach what you’ve learned in the form of a blog you can see the gaps in your knowledge and fill them in” — My Manager (2019)“創建一個博客以鞏固您所學到的東西。 當您以博客的形…

D3.js 加標簽

條形圖還可以配上實際的數值,我們通過文本元素添加數據值。 svg.selectAll("text").data(dataset).enter().append("text").text(function(d){return d;}) 通過 x 和 y 值來定位文本元素。 .attr("text-anchor", "middle").attr("…

oppo5.0以上機器(親測有效)激活Xposed框架的教程

對于喜歡玩手機的朋友而言&#xff0c;常常會用到xposed框架以及種類繁多功能強大的模塊&#xff0c;對于5.0以下的系統版本&#xff0c;只要手機能獲得ROOT權限&#xff0c;安裝和激活xposed框架是異常簡便的&#xff0c;但隨著系統版本的迭代&#xff0c;5.0以后的系統&#…

和matlab一樣的輕量級

Python&#xff08;英國發音&#xff1a;/?pa?θ?n/ 美國發音&#xff1a;/?pa?θɑ?n/&#xff09;, 是一種面向對象、解釋型計算機程序設計語言&#xff0c;由Guido van Rossum于1989年發明&#xff0c;第一個公開發行版發行于1991年。Python是純粹的自由軟件&#xff…

熊貓分發_流利的熊貓

熊貓分發Let’s uncover the practical details of Pandas’ Series, DataFrame, and Panel讓我們揭露Pandas系列&#xff0c;DataFrame和Panel的實用細節 Note to the Readers: Paying attention to comments in examples would be more helpful than going through the theo…

redis tomcat session

本機ip為192.168.1.101 1、準備測試環境 兩個Tomcat 在Eclipse中新建2個Servers&#xff0c;指定對應的Tomcat&#xff0c;端口號錯開。 Tomcat1&#xff08;18005、18080、18009&#xff09; Tomcat2&#xff08;28005、28080、28009&#xff09; 一個Redis Redis下載官網&…

Fiddler抓包-只抓APP的請求

from:https://www.cnblogs.com/yoyoketang/p/6582437.html fiddler抓手機app的請求&#xff0c;估計大部分都會&#xff0c;但是如何只抓來自app的請求呢&#xff1f; 把來自pc的請求過濾掉&#xff0c;因為請求太多&#xff0c;這樣會找不到重要的信息了。 環境準備&#xff1…

技術分享 | 基于EOS的Dapp開發

區塊鏈技術是當前最能挑動社會輿論神經&#xff0c;激起資本欲望的現象級技術。去中心化的價值互聯&#xff0c;信用共識&#xff0c;新型組織構架&#xff0c;新的生產關系和智能合約&#xff0c;顛覆法幣的發行流通體系和記賬體系。這些新的技術都讓人充滿想象&#xff0c;充…

DOCKER windows 安裝Tomcat內容

DOCKER windows安裝 DOCKER windows安裝 1.下載程序包2. 設置環境變量3. 啟動DOCKERT4. 分析start.sh5. 利用SSH工具管理6. 下載鏡像 6.1 下載地址6.2 用FTP工具上傳tar包6.3 安裝6.4 查看鏡像6.5 運行 windows必須是64位的 1.下載程序包 安裝包 https://github.com/boot2doc…

python記錄日志_5分鐘內解釋日志記錄—使用Python演練

python記錄日志Making your code production-ready is not an easy task. There are so many things to consider, one of them being able to monitor the application’s flow. That’s where logging comes in — a simple tool to save some nerves and many, many hours.使…

理解 Linux 中 `ls` 的輸出

理解 Linux 中 ls 的輸出ls 的輸出會因各 Linux 版本變種而略有差異&#xff0c;這里只討論一般情況下的輸出。 下面是來自 man page 關于 ls 的描述&#xff1a; $ man ls ls - list directory contents 列出文件夾中的內容。 但一般我們會配合著 -l 參數使用&#xff0c;將輸…

鎖表的進程和語句,并殺掉

查看鎖表進程SQL語句1&#xff1a; select sess.sid, sess.serial#, lo.oracle_username, lo.os_user_name, ao.object_name, lo.locked_mode from v$locked_object lo, dba_objects ao, v$session sess where ao.object_id lo.object_id and lo.session_id sess.sid; 查看鎖…

p值 t值 統計_非統計師的P值

p值 t值 統計Here is a summary of how I was taught to assess the p-value in hopes of helping some other non-statistician out there.這是關于如何教會我評估p值的摘要&#xff0c;希望可以幫助其他一些非統計學家。 P-value in Context上下文中的P值 Let’s start wit…

獲取對象屬性(key)

for…in方法Object.keysObject.getOwnPropertyNames關于對象的可枚舉性&#xff08;enumerable&#xff09; var obj {a: 1,b: 2 } Object.defineProperty(obj, c, {value: 3,enumerable: false }) 復制代碼enumerable設置為false&#xff0c;表示不可枚舉&#xff0c;for…in…

github免費空間玩法

GitHub 是一個用于使用Git版本控制系統的項目的基于互聯網的存取服務,GitHub于2008年2月運行。在2010年6月&#xff0c;GitHub宣布它現在已經提供可1百萬項目&#xff0c;可以說非常強大。 Github雖然是一個代碼倉庫&#xff0c;但是Github還免費為大家提供一個免費開源Github …

用php生成HTML文件的類

目的 用PHP生成HTML文檔, 支持標簽嵌套縮進, 支持標簽自定義屬性 起因 這個東西確實也是心血來潮寫的, 本來打算是輸出HTML片段用的, 但后來就干脆寫成了一個可以輸出完整HTML的功能; 我很滿意里邊的實現縮進的機制, 大家有用到的可以看看p.s. 現在都是真正的前后端分離了(vue,…