As always, when you want to iterate over iterables taking the values in the same position, but the iterables are of different lengths, use zip_longest
. This will have an automatic fill-value of None
.
In [1]: from itertools import zip_longest
In [2]: data = {"move1": {"recording1": "somedata1", "recording2": "somedata2", "recording3": "somedata3"},
...: "move2": {"recordingA": "somedata4", "recordingB": "somedata5"},
...: "move3": {"recordingI": "somedata6"}}
In [3]: for group in zip_longest(*map(dict.items, data.values()), fillvalue=None):
...: result = {k:{} if v is None else dict([v]) for k,v in zip(data, group)}
...: print("="*100)
...: print(result)
...:
====================================================================================================
{'move1': {'recording1': 'somedata1'}, 'move2': {'recordingA': 'somedata4'}, 'move3': {'recordingI': 'somedata6'}}
====================================================================================================
{'move1': {'recording2': 'somedata2'}, 'move2': {'recordingB': 'somedata5'}, 'move3': {}}
====================================================================================================
{'move1': {'recording3': 'somedata3'}, 'move2': {}, 'move3': {}}
I reconstituted the dicts you wanted into result
, although, that honestly doesn't make a lot of sense. You should probably just work with what the zip_longest
iterator is providing you. But at least this demonstrates the basic idea.
Edit
If you are working with lists, you can do something even more simple. Something like:
In [6]: data = {"move1": ["somedata1", "somedata2", "somedata3"],
...: "move2": ["somedata4", "somedata5"],
...: "move": ["somedata6"]}
In [7]: for group in zip_longest(*data.values()):
...: print("="*100)
...: result = dict(zip(data, group))
...: print(result)
...:
====================================================================================================
{'move1': 'somedata1', 'move2': 'somedata4', 'move': 'somedata6'}
====================================================================================================
{'move1': 'somedata2', 'move2': 'somedata5', 'move': None}
====================================================================================================
{'move1': 'somedata3', 'move2': None, 'move': None}
I didn't convert the values of the results to single-element / empty lists because that doesn't really make a lot of sense. If you really need that, you should be able to take it from here.