[{'a': {'b':1, 'c':2}}, {'a': {'d':3, 'e':4}}]
如何转换成下面的结构,也就是不同字典里相同 key 的值,如何将对应的 value 合并,并组成一个新的字典
{'a':{'b':1, 'c':2, 'd':3, 'e':4}}
谢谢大家,求支招
1
lhx2008 2019-11-20 18:37:01 +08:00 via Android
for 一下不就好了,字典合并有方法
|
2
anonymous256 2019-11-20 18:46:35 +08:00 via Android
print(your_list[0].update(your_list[1]))
|
3
anonymous256 2019-11-20 18:54:19 +08:00 via Android
测试了下,不可以这样写,而且 update 是不返回结果
|
5
Tianny OP @anonymous256 是的。而且 update 会覆盖具有相同 key 的 value
|
6
wuwukai007 2019-11-20 18:59:17 +08:00
你是单独的一个 a,还是好多个不同的 键,那要分组了
|
7
ClericPy 2019-11-20 18:59:59 +08:00 1
|
8
cherbim 2019-11-20 19:03:41 +08:00
好像之能 for 循环更新键值
|
9
anonymous256 2019-11-20 19:07:05 +08:00
l = [{'a': {'b': '1'}, 'b': '2'}, {'a': {'c': '3'}}]
empty = {} for item in l: for k, v in item.items(): if k in empty: empty[k].update(v) else: empty[k] = v print(empty) 输出: {'a': {'b': '1', 'c': '3'}, 'b': '2'} 大致是这样了, 实际的数据可能比这个复杂一点 |
10
anonymous256 2019-11-20 19:08:34 +08:00
重发一下
l = [{'a': {'b': '1'}, 'b': '2'}, {'a': {'c': '3'}}] empty = {} for item in l: ....for k, v in item.items(): ........if k in empty: ............empty[k].update(v) ........else: ............empty[k] = v print(empty) 输出: {'a': {'b': '1', 'c': '3'}, 'b': '2'} |
11
wuwukai007 2019-11-20 19:21:48 +08:00 1
a=[{'a': {'b':1, 'c':2}}, {'a': {'d':3, 'e':4}},{'b':{'q':5}},{'b':{'z':7}}]
res = pd.DataFrame(a).T res.mask(res.isna(),None,inplace=True) dict_1 = {} buffer = {} for key,value in res.iterrows(): ----x = [buffer.update(i) for i in value if i is not None] ----dict_1[key] = buffer.copy() ----buffer.clear() dict_1 >>> {'a': {'b': 1, 'c': 2, 'd': 3, 'e': 4}, 'b': {'q': 5, 'z': 7}} |
13
andylsr 2019-11-20 19:51:45 +08:00 via Android
用 defaultdict,直接对值 update
|
14
andylsr 2019-11-20 20:05:21 +08:00 1
@andylsr
In [1]: from collections import defaultdict In [2]: result = defaultdict(dict) In [3]: items = [{'a': {'b':1, 'c':2}}, {'a': {'d':3, 'e':4}}] In [4]: for item in items: ...: for k, v in item.items(): ...: result[k].update(v) ...: result Out[4]: defaultdict(dict, {'a': {'b': 1, 'c': 2, 'd': 3, 'e': 4}}) |
15
Latin 2019-11-21 14:22:39 +08:00 1
...: lst = [{'a': 123}, {'a': 456},{'b': 789}]
...: ...: temp = {} ...: for _ in lst: ...: for k, v in _.items(): ...: dic.setdefault(k, []).append(v) ...: ...: print([{k:v} for k, v in dic.items()]) ...: ...: ...: ...: [{'a': [123, 456]}, {'b': [789]}] |
16
yucongo 2019-11-27 13:25:45 +08:00
from functools import reduce
lst = [{'a': {'b':1, 'c':2}}, {'a': {'d':3, 'e':4}}] data = reduce(lambda x, y: {**x, **y}, [elm.get('a') for elm in lst]) {'a': data} #-> {'a': {'b': 1, 'c': 2, 'd': 3, 'e': 4}} |