首页 > 解决方案 > 我们如何合并字典的键值?

问题描述

我有字典

[{'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"])]

标签: pythondictionary

解决方案


如果我正确理解了您的问题,则“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']}

推荐阅读