如何在Python 3中將列表用作字典的鍵?

WBOY
發布: 2023-08-28 20:57:02
轉載
1675 人瀏覽過

如何在Python 3中将列表用作字典的键?

字典是Python程式語言中最強大的資料結構之一。這是一個由鍵值對組成的資料結構。它具有幾個優點;例如,存取值的時間複雜度為O(1),它在記憶體上高效,易於更新、刪除和迭代,並提供許多內建函數進行快速操作。

當直接使用清單時出現的問題

我們專注於這個主題,因為當我們嘗試將清單作為鍵時會出現問題。列表是Python中的可變資料類型。因此,我們可以在清單內部刪除、更新和追加值。因此,如果我們從列表和列表項產生一個雜湊函數,當列表的項發生變化時,我們將無法再找到雜湊函數,因為雜湊函數已經改變。

另一個潛在的問題是不同的列表可能具有相同的雜湊值。如果兩個列表的值總和相同,它們的雜湊值也會相同。在這種情況下,如果將其中一個列表用作字典中的鍵,並且搜尋具有相同雜湊值的另一個列表,字典可能會給出錯誤的結果。

Convert The List To Tuple

一種將字典的鍵列表轉換為元組並將其用作鍵的方法是使用這種間接方式。請注意,儘管值保持不變,但資料類型不再是列表

文法

<variable name> = tuple(<list to convert into tuple>)
登入後複製

Here the tuple takes one parameter, which is the list's name.

Example

In the following code, we first created an empty dictionary named my_dict. Next, we created our list named my_list. We used the tuple method to convert the list into a Tuple object. We used the tuple method to convert the list into a Tuple object. We a string "hello, world!" as the value.

my_dict = {}
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
my_dict[my_tuple] = "Hello, World!"
print(my_dict)
登入後複製

Output

#
{(1, 2, 3): 'Hello, World!'}
登入後複製

將清單轉換為字串

另一種方法是將清單轉換為字串資料類型。字串也是不可變的資料類型;因此,我們可以將其用作字典的鍵。

文法

<variable name> = ''.join(str(e) for e in <name of the list>)
登入後複製

這裡的語句從列表中取得各個元素,並將其組合成一個字串。 Join函數將字串序列連接起來。

Example

In the following code, we first created a list named my_list. Next, we used the join method that creates a string of list elements. Since the string can be used as the dictionary key, weas ed 是dictionary my_list_str.

my_list = [1, 2, 3]
my_list_str = ''.join(str(e) for e in my_list)
my_dict = {my_list_str: 'value'}
print(my_dict)
print(my_dict[my_list_str])
登入後複製

Output

#
{'123': 'value'}
value
登入後複製

將列表轉換為JSON

We can also use the JSON module and built-in functions to convert the list first to string using the dumps method and later use this as the dictionary's key.

文法

<name of variable< = json.dumps(<name of list<)
登入後複製

這裡是JSON函式庫的dumps方法,它將Python物件序列化為JSON格式的字串。 dumps方法接受字串的名稱作為參數

Example

在下面的程式碼中,我們先匯入了JSON函式庫。接下來,我們建立了一個名為my_list的清單。我們使用dumps方法從列表建立了一個序列化物件。現在,我們將序列化物件作為字典鍵my_dict。

import json
my_list = [1, 2, 3]
my_key = json.dumps(my_list)
my_dict = {my_key: 'value'}
print(my_dict)
登入後複製

Output

#
{'[1, 2, 3]': 'value'}
登入後複製

Conclusion

In this article, we learned how to use lists as the key of a dictionary in Python 3. We understood the difficulties we faced if we directly tried to make the lists as the keys in the Python diction dical the Python dical. convert the list data type to tuples, strings, etc., which are immutable data types. We also learned how to use the JSON module to use lists as the dictionary key.

以上是如何在Python 3中將列表用作字典的鍵?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!