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

WBOY
WBOY 转载
2023-08-28 20:57:02 746浏览

如何在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 now used the Tuple object as the key as 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, we used this as te key of the 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 dictionary. Therefore we first need to 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,如有侵犯,请联系admin@php.cn删除