How can I split a dictionary with 2 values per key into two dictionaries, one for the first value and one for the second value?
That is, how do I turn this d = {'a':['val1', 'val2'], 'b': ['val1', 'val2']}
into:
d1 = {"a": "val1", "b": "val1"}
d2 = {"a": "val2", "b": "val2"}
Python 3.7
CodePudding user response:
If you'll always have two values, this is pretty straightforward with two dict comprehensions:
>>> d1 = {k: v[0] for k, v in d.items()}
>>> d2 = {k: v[1] for k, v in d.items()}
>>> d1
{'a': 'val1', 'b': 'val1'}
>>> d2
{'a': 'val2', 'b': 'val2'}
CodePudding user response:
Try:
d = {"a": ["val1", "val2"], "b": ["val1", "val2"]}
d1, d2 = (dict(zip(d, vals)) for vals in zip(*d.values()))
print(d1)
print(d2)
Prints:
{'a': 'val1', 'b': 'val1'}
{'a': 'val2', 'b': 'val2'}
CodePudding user response:
Here's a simple list comprehension over all the values in the dictionary that should work for any list length (including mismatched lengths -- shorter lists will just not be represented in all of the result dicts):
>>> d = {'a':['val1', 'val2'], 'b': ['val1', 'val2']}
>>> n_dicts = [
... {k: v[i] for k, v in d.items() if i < len(v)}
... for i in range(max(len(v) for v in d.values()))
... ]
>>> n_dicts
[{'a': 'val1', 'b': 'val1'}, {'a': 'val2', 'b': 'val2'}]
You can of course destructure this into two variables if you want:
>>> d1, d2 = n_dicts
>>> d1
{'a': 'val1', 'b': 'val1'}
>>> d2
{'a': 'val2', 'b': 'val2'}
but leaving it as a list makes it easier for your code to handle different numbers of elements/dicts.
CodePudding user response:
As an addendum to sj95126's answer, if the dimensions of the lists are unknown:
d = {'a':['val1', 'val2'], 'b': ['val1', 'val2']}
[{k: d[k][i] for k in d} for i in range(min(map(len, d.values())))]
# [{'a': 'val1', 'b': 'val1'},
# {'a': 'val2', 'b': 'val2'}]