-6

在 python 中,我有一个如下所示的字典

{'key1': [L1, L2],
 'key2': [P1, P2],
 'key3': [T1],
 'key4': [V1]}

所需的输出是

{'key1': [L1], 'key2': [P1], 'key3': [T1], 'key4': [V1]},
{'key1': [L2], 'key2': [P2], 'key3': [T1], 'key4': [V1]}

任何帮助!

4

3 回答 3

1
>>> # Let's suppose your dictionary looks something like
>>> some_dict = {'key1': ['L1', 'L2'],
 'key2': ['P1', 'P2'],
 'key3': ['T1'],
 'key4': ['V1']}
>>> #First determine the longest value sequence
>>> max_len = len(max(some_dict.values(), key = len))
>>> #assimilate your tools
>>> from itertools import izip, cycle, islice
>>> #Create the value sequence
>>> value = islice(izip(*(cycle(e) for e in some_dict.values())), max_len)
>>> #recreate the dictionary
>>> [dict(izip(some_dict.keys(), e)) for e in value]
[{'key3': 'T1', 'key2': 'P1', 'key1': 'L1', 'key4': 'V1'}, {'key3': 'T1', 'key2': 'P2', 'key1': 'L2', 'key4': 'V1'}]
>>> 

注意,如果顺序很重要,请使用 anOrderedDict而不是内置的 dict。

于 2013-02-25T18:29:34.443 回答
1
In [1]: d = {'key1': ['L1', 'L2'],  
 'key2': ['P1', 'P2'],
 'key3': ['T1'],
 'key4': ['V1']}

In [2]: [{k: [v[min(i, len(v)-1)]] for k, v in d.items()}
     for i in range(max(map(len, d.values())))]
Out[2]: 
[{'key1': ['L1'], 'key2': ['P1'], 'key3': ['T1'], 'key4': ['V1']},
 {'key1': ['L2'], 'key2': ['P2'], 'key3': ['T1'], 'key4': ['V1']}]
于 2013-02-25T18:19:25.450 回答
0

这并不能完全满足您的要求,因为我不确定您为什么需要['T1']['V1']再次复制:

d = {'key1': ['L1', 'L2'],
 'key2': ['P1', 'P2'],
 'key3': ['T1'],
 'key4': ['V1']}
print [{key:d[key][i] for key in d.keys() for i in range(len(d[key]))}, {key:d[key][i] for key in d.keys() for i in range(len(d[key])-1)}]

结果是:

[{'key3': 'T1', 'key2': 'P2', 'key1': 'L2', 'key4': 'V1'}, {'key2': 'P1', 'key1': 'L1'}]
于 2013-02-25T18:31:49.507 回答