如何合并字典的键值?

时间:2019-05-13 19:33:09

标签: python dictionary

我有字典

[{'a': 'tc1', 'b': 'tc2'}, {'a': 'tc1', 'b': 'tc3'}]

我要创建结果字典

result = {'tc1':['tc2', 'tc3']}

有什么想法我们可以做到吗?

js = [{'a': 'tc1', 'b': 'tc2'}, {'a': 'tc1', 'b': 'tc3'}]
ls =[]
for i in js:
     x[i['a']]= ls+[(i["b"])]

2 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,则'a'元素将始终是新字典的键,而'b'元素将始终是其值。然后以下代码将为您工作:

js = [{'a': 'tc1', 'b': 'tc2'}, {'a': 'tc1', 'b': 'tc3'}]
result = {}  # Create the empty result dictionary
for i in js:
    k, v = i['a'], i['b']  # k will be the key, v will be the value
    if k not in result:  # If k is not a key of result yet, we create the entry as an empty list
        result[k] = []
    # By now, we know that k is a key in result. Now we add the value.
    result[k].append(v)
print result # {'tc1': ['tc2', 'tc3']}

答案 1 :(得分:0)

您可以使用functools中的reduce:

lst = [{'a': 'tc1', 'b': 'tc2'}, {'a': 'tc1', 'b': 'tc3'}]
from functools import reduce
m = reduce(lambda m,kv: m.setdefault(kv[0],[]).append(kv[1]) or m, (kv for d in lst for kv in d.items()), dict() )
print(m) # {'a': ['tc1', 'tc1'], 'b': ['tc2', 'tc3']}

转换为以下程序代码:

m = dict()
for d in lst:
    for k,v in d.items():
        m.setdefault(k,[]).append(v)