簡體   English   中英

如何根據鍵從字典中檢索值?

[英]How to retrieve value from a dictionary based on key?

我被這個小問題困住了很長一段時間,不明白為什么。

假設我有一個列表:

test = ['1', '2', '3']

我將其轉換為字典使用

test_dict =  { i : test[i] for i in range(0, len(test))}

{0: '1', 1: '2', 2: '3'}

現在,當我根據這樣的值訪問密鑰時

print (a.get('1')) 

它給了我無。 在這方面的任何建議都會有所幫助。

它的類型問題

test_dict =  { i : test[i] for i in range(0, len(test))}

{0: '1', 1: '2', 2: '3'}

鍵將是整數類型而不是字符串類型。

試試這個

print (a.get(1))

編輯:要獲取密鑰,您可以翻轉字典創建

test_dict =  { test[i] : i for i in range(0, len(test))}

print (a.get(1))
0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM