我能够实现这一目标,但我认为必须有更好的方法。我们的想法是为这两种情况提供共同的解决方案。
问题:
a& b是两本词典。这些字典的值可以是简单的字符串(用例1)或相同长度的列表(用例2)。请注意,这些列表的长度可能会因a&而异。 b(例如: - 用例2中的键' 2')但同一字典中的长度相同。
预期:
我们需要创建一个最终字典,其中包含来自字典a& b并将这些值(无论是字符串还是列表)合并为长度相当于任一字典中最长的列表。例如: - 在用例2中,键2在字典a中有[" abc"," def"]但在字典b中只有[" abc"]。在这里,我们期待最终结果为2:[" abc"," def"," abc",None]。
示例:
用例1:
a = {1:"xyz",2:999,3:1234,4:"boy"}
b = {1:"xyz",2:99,3:19,6:"toy"}
Result expected : {1: ['xyz', 'xyz'], 2: [999, 99], 3: [1234, 19], 4: ['boy', None],
6: ['None', 'toy']
用例2:
a = {1:["xyz","123"],2:["abc","def"],3:["zzz",""],4:["boy","abc"]}
b = {1:["xyz","1234"],2:["abc"],3:["zz",""], 6: ["toy"]}
result expected: {1: [('xyz', 'xyz'), ('123', '1234')], 2: [('abc', 'abc'), ('def', None)],
3: [('zzz', 'zz'), ('', '')], 4: [('boy', None), ('abc', None)],
6: [(None, 'toy')]})
答案 0 :(得分:1)
算法:
from itertools import izip_longest
def merge(a, b):
res = {}
keys = set(a.keys()) | set(b.keys())
if isinstance(a.values()[0], list):
res = {k: list(izip_longest(a.get(k, [None]), b.get(k, [None]))) for k in keys}
else:
res = {k: [a.get(k, None), b.get(k, None)] for k in keys}
return res
a = {1:"xyz",2:999,3:1234,4:"boy"}
b = {1:"xyz",2:99, 3:19, 6:"toy"}
exp = {1: ['xyz', 'xyz'],
2: [999, 99],
3: [1234, 19],
4: ['boy', None],
6: [None, 'toy']}
print merge(a, b) == exp
输出:
True
a = {1:["xyz","123"], 2:["abc","def"],3:["zzz",""],4:["boy","abc"]}
b = {1:["xyz","1234"],2:["abc"], 3:["zz",""], 6: ["toy"]}
exp = {1: [('xyz', 'xyz'), ('123', '1234')],
2: [('abc', 'abc'), ('def', None)],
3: [('zzz', 'zz'), ('', '')],
4: [('boy', None), ('abc', None)],
6: [(None, 'toy')]}
print merge(a, b) == exp
输出:
True
注意 Python 2