# 最终想要这个类型的数据 {"key": ["a", "b"]}
mylist= {"key": [{'a': '1'}, {'b': '2'}]}
all = {}
for k, v in mylist.items():
for j in v:
all.setdefault(j, []).append(j.keys())
# TypeError: unhashable type: 'dict' 怎么设置字典的 value 默认类型是 list,且可以 append?
1
JacHammer 2020-08-24 22:15:34 +08:00
```python
mylist= {"key": [{'a': '1'}, {'b': '2'}]} all = {"key": []} for k, v in mylist.items(): for j in v: all['key'] += j.keys() ``` |
3
maddevil 2020-08-24 22:42:14 +08:00
```
mylist = {"key": [{'a': '1'}, {'b': '2'}]} all = {} for k, v in mylist.items(): all[k] = [] for j in v: all[k] += j.keys() ``` |
4
Trim21 2020-08-24 22:47:01 +08:00
'dict' 怎么设置字典的 value 默认类型是 list,且可以 append?
from collections import defaultdict d = defaultdict(list) d[1].append(2) print(d[1]) |
5
maddevil 2020-08-24 22:51:48 +08:00
其实还可以一行搞定:
{k: [j for i in v for j in i.keys()] for k, v in mylist.items()} |
6
GoLand 2020-08-24 22:53:43 +08:00
In [30]: example = {'key': [{'a': '1'}, {'b': '2', 'c': '3'}], 'key2': [{'c': 1}, {'d': 2}]}
In [31]: res = {} In [32]: for k, v in example.items(): ...: res[k] = list(itertools.chain.from_iterable(map(lambda x: x.keys(), v))) ...: In [33]: res Out[33]: {'key': ['a', 'b', 'c'], 'key2': ['c', 'd']} |
7
h272377502 2020-08-25 11:19:20 +08:00
楼主什么操作,j 的 type 是 dict,dict 是 unhashable 的对象,你的目的明明是以 k 作为 value 。。。
最后一行改成这样吧 all.setdefault(k, []).append(list(j.keys())) |
8
css3 OP |
9
biglazycat 2020-09-06 21:27:57 +08:00
mylist= {"key": [{'a': '1'}, {'b': '2'}]}
all = {} for k, v in mylist.items(): for j in v: all.setdefault(k, []).append(list(j.keys())[0]) print(all) |