简体   繁体   English

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

[英]How do i change a list of values in a dictionary to a set of values?

So inside the dictionary, I have values that are lists with [] brackets.所以在字典里面,我的值是带 [] 括号的列表。 But I want to change them into {} brackets.但我想把它们改成 {} 括号。 Does anyone have any idea how to do this?有谁知道如何做到这一点?

From:从:

{hello: ['1', '2', '3']}

To:到:

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

You can convert the list inside the dictionary into a set like you would with any other list, too:您也可以像处理任何其他列表一样将字典中的列表转换为一个集合:

>>> a = {'hello': ['1', '2', '3']}
>>> a
{'hello': ['1', '2', '3']}
>>> a['hello'] = set(a['hello'])
>>> a
{'hello': {'2', '3', '1'}}

Sets aren't ordered, which explains the mixed-up order of {'2', '3', '1'} .集合没有排序,这解释了{'2', '3', '1'}的混合顺序。

Also, you didn't define your dictionary key hello in your question so I used a simple string here.另外,您没有在问题中定义字典键hello所以我在这里使用了一个简单的字符串。

Assuming "hello" is a variable:假设“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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM