python - 我们如何合并字典的键值?
问题描述
我有字典
[{'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"])]
解决方案
如果我正确理解了您的问题,则“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']}
推荐阅读
- python - 如何使用列表推导对开始到结束范围内的数字进行平方?
- c# - 如何选择一个值来填充密封类中的两个值
- c# - 单元测试在 using 语句中返回的流(因此关闭)
- angular - 如何在ngrx / store测试中为特定选择器返回假/存根值?
- python - 覆盆子 pi pip install psychopy HDF5 not found
- swift - UICollectionViewCell cellforItemAt:带数组
- java - 数独游戏的标记数字
- wpf - 单击 UserControl 中的 Button 以将值设置为 MainWindow 的 columndefinition
- angular - 带有锚标记(划分)刷新的角度 URL 转到主页
- java - 关于 Java 中的 REST 请求和输出/输入流的说明