0

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?

Community
  • 1
  • 1
Brita
  • 15
  • 7
  • Suggestion: Whether the multiple values are stored as lists or sets, you should consider also making the single values the same type because it will make processing the value of an arbitrary key much easier later on — in other words, make _all_ the values the same container type even those that contain fewer than two items. The only exception might be for known keys that can never have more than a single item associated with them. – martineau Apr 29 '16 at 17:56

3 Answers3

3

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.

MSeifert
  • 145,886
  • 38
  • 333
  • 352
1

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'}}
julienc
  • 19,087
  • 17
  • 82
  • 82
0

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.

akaIDIOT
  • 9,171
  • 3
  • 27
  • 30