我有以下列表的字典:
dict1 = {'SourceName': ['PUICUI'], 'EventType': ['XYX'], 'TableName': ['XYX__ct'], 'KeyIndex': ['XYX', 'ZXX']}
dict2 = {'SourceName': ['PUICI2'], 'EventType': ['XYX'], 'TableName': ['ZXX__ct1']}
下面的代码按预期运行。
def combineDictList(*args):
result = {}
for dic in args:
for key in (result.keys() | dic.keys()):
if key in dic:
result.setdefault(key, []).extend(dic[key])
return result
print(combineDictList(dict1, dict2))
这给了我
{'TableName': ['XYX__ct', 'ZXX__ct1'], 'SourceName': ['PUICUI', 'PUICI2'], 'KeyIndex': ['XYX', 'ZXX'], 'EventType': ['XYX', 'XYX']}
但是我的问题是如何将最终结果打印为具有唯一值,例如这里EventType
具有相同的值。
所以,在最终结果中,我只会期望最终结果是
{'TableName': ['XYX__ct', 'ZXX__ct1'], 'SourceName': ['PUICUI', 'PUICI2'], 'KeyIndex': ['XYX', 'ZXX'], 'EventType': ['XYX']}
反正我能做到吗?
答案 0 :(得分:2)
尝试一下
def combineDictList(*args):
result = {}
for dic in args:
for key in (result.keys() | dic.keys()):
if key in dic:
result.setdefault(key, []).extend(dic[key])
result[key] = list(set(result[key]))
return result
print(combineDictList(dict1, dict2))
答案 1 :(得分:1)
使用set
例如:
dict1 = {'SourceName': ['PUICUI'], 'EventType': ['XYX'], 'TableName': ['XYX__ct'], 'KeyIndex': ['XYX', 'ZXX']}
dict2 = {'SourceName': ['PUICI2'], 'EventType': ['XYX'], 'TableName': ['ZXX__ct1']}
def combineDictList(*args):
result = {}
for dic in args:
for k, v in dic.items():
result.setdefault(k, set()).update(v)
# If you need values as list
# result = {k: list(v) for k, v in result.items()}
return result
print(combineDictList(dict1, dict2))
输出:
{'EventType': {'XYX'},
'KeyIndex': {'ZXX', 'XYX'},
'SourceName': {'PUICI2', 'PUICUI'},
'TableName': {'ZXX__ct1', 'XYX__ct'}}