问题描述:

I have a dictionary where I have the data already inside, i.e. keys have values and some of them have more than one value.

For example:

i = {"a": "111", "b": "222", "c": ["333", "444"]}

How can I change the type of the multiple values? I want them to be sets, not lists, such as:

i = {"a": {"111"}, "b": {"222"}, "c": {"333", "444"}}

One similar post is this one:

How to add multiple values to a dictionary key in python? [closed]

There it is explained how to add multiple elements to a dictionary, but they always seem to be lists.

How to change the type of the multiple values?

OR how to add them to the dictionary as sets, not lists?

网友答案:

In a single line of code:

>>> i = {"a": "111", "b": "222", "c": ["333", "444"]}
>>> {k: set(v) for k, v in i.items()}
{'b': {'2'}, 'a': {'1'}, 'c': {'444', '333'}}

Or with a few more steps:

>>> i = {"a": "111", "b": "222", "c": ["333", "444"]}
>>> for k, v in i.items():
...     i[k] = set(v)
>>> i
{'b': {'2'}, 'a': {'1'}, 'c': {'444', '333'}}
网友答案:

Using a dict-comprehension makes converting an existing dict very easy:

i = {"a": "111", "b": "222", 'c': ["333", "444"]}
{k: set(v) if isinstance(v, list) else v for k, v in i.items()}

this converts all values that are lists to sets.

网友答案:

Instead of doing

my_dict['key'] = ['333', '444']

use a set literal:

my_dict['key'] = {'333', '444'}

That looks like a dict literal, but the lack of key: value like things makes it a set.

相关阅读:
Top