Python 如何将字典中的值列表更改为一组值?

Python 如何将字典中的值列表更改为一组值?,python,Python,因此,在字典中,我有一些值,它们是带有[]方括号的列表。但我想把它们改成{}括号。有人知道怎么做吗 发件人: 致: 您也可以将字典中的列表转换为一个集合,就像处理任何其他列表一样: >>> a = {'hello': ['1', '2', '3']} >>> a {'hello': ['1', '2', '3']} >>> a['hello'] = set(a['hello']) >>> a {'hello': {'2',

因此,在字典中,我有一些值,它们是带有[]方括号的列表。但我想把它们改成{}括号。有人知道怎么做吗

发件人:

致:


您也可以将字典中的列表转换为一个集合,就像处理任何其他列表一样:

>>> a = {'hello': ['1', '2', '3']}
>>> a
{'hello': ['1', '2', '3']}
>>> a['hello'] = set(a['hello'])
>>> a
{'hello': {'2', '3', '1'}}
集合没有顺序,这解释了
{'2','3','1'}
的混淆顺序

另外,您的问题中没有定义字典键
hello
,因此我在这里使用了一个简单的字符串。

假设“hello”是一个变量:

 d = {hello: ['1', '2', '3']}
 dn = { k: set(v) for k, v in d.items() } #iterate through the dict and replace the lists by sets

dict
应该包含成对的
{key:value}
;它是一个集合。
hello
不是字典的有效键-它是一个未定义的变量。请添加一个工作表,包括您尝试执行的操作。
>>> a = {'hello': ['1', '2', '3']}
>>> a
{'hello': ['1', '2', '3']}
>>> a['hello'] = set(a['hello'])
>>> a
{'hello': {'2', '3', '1'}}
 d = {hello: ['1', '2', '3']}
 dn = { k: set(v) for k, v in d.items() } #iterate through the dict and replace the lists by sets