-4

I named it dict1, for example, but in fact I use a dictionary from the Internet, which I can't rewrite initially.The values are set.

dict1 = {'cats':{'1','2'},
        'dogs':{'1'}}

Output:

{'cats': {'1', '2'}, 'dogs': {'1'}}

I want the values to be an array, not a dictionary. Output i want:

{'cats': ['1', '2'], 'dogs': ['1']}
Rory
  • 471
  • 2
  • 11
  • Does this answer your question? [How can I convert a dictionary into a list of tuples?](https://stackoverflow.com/questions/674519/how-can-i-convert-a-dictionary-into-a-list-of-tuples) – msanford Jan 17 '22 at 14:21
  • 7
    The values are _sets_, not dictionaries. It's unclear how you're making the dictionary, but it you want lists why _are_ they sets to start with? – jonrsharpe Jan 17 '22 at 14:21
  • I created example, in reality I use a dictionary that I can't set initially – Rory Jan 17 '22 at 14:31
  • 1
    @SashSinha that's a possibility - my point is that without some context from the OP we can't know that. What does "from the internet" mean, for example (sets aren't part of JSON)? – jonrsharpe Jan 17 '22 at 14:31
  • Yes, I actually use a dictionary to delete stop words that are not in the library. So I downloaded a file from github that has this structure. – Rory Jan 17 '22 at 14:34

2 Answers2

2

You can do:

dict2 = {k: list(v) for k, v in dict1.items()} 
Neb
  • 2,270
  • 1
  • 12
  • 22
2

One approach is to use a for loop to parse the dictionary and convert each value to a Python list (which is presumably what you mean, when you use the term array).

dict1 = {'cats':{'1','2'},
        'dogs':{'1'}}

for key, value in dict1.items():
    dict1[key] = list(value)
dict1

Yields:

{'cats': ['1', '2'], 'dogs': ['1']}

As has indicated by @neb, you can "simplify" this by creating a dictionary comprehension (which makes the code a one-liner and potentially produces the end result faster due to under the hood optimizations, but may be less readable/intuitive for folks new to Python).

dict1 = {key: list(value) for key, value in dict1.items()} 

Also yields:

{'cats': ['1', '2'], 'dogs': ['1']}

Difference between sets and dictionaries:

As noted in the comments, several folks have indicated that this

{'1', '2'}

is NOT a dictionary, it is a Python set. When printed to the screen, a set may superficially look like a dict, because of the brackets (which are used for sets and dicts), but we can see that the data object lacks the key differentiator: the colon to separate a key from a value as shown here in these example dicts.:

{'1': '2'}
{'key': 'value', 'key1': 'value2'}
E. Ducateme
  • 4,028
  • 2
  • 20
  • 30