Turn dictionary values into an array python [closed]
Solution 1:
You can do:
dict2 = {k: list(v) for k, v in dict1.items()}
Solution 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'}