现在有一个字典 a: a = { '0106': '50', '0117': '35', '0203': '30', '0205': '30', '3302': '45', '3305': '45' } 如何根据 key 值前面的两位数拆分成字典 b: b = { '01': { '0106': '50', '0117': '35', }, '02': { '0203': '30', '0205': '30', }, '33': { '3302': '45', '3305': '45', } }
请问大神用 python 代码如何优雅的实现?
1
aaronzjw 2018-05-11 17:44:54 +08:00 via iPhone
collection defaultdict 了解一下
|
2
alvin666 2018-05-11 17:49:31 +08:00 via Android
b={{}}
for key,value in a.items(): b[key[:2][key]]=value |
3
xpresslink 2018-05-11 17:51:35 +08:00 1
>>> a = { '0106': '50', '0117': '35', '0203': '30', '0205': '30', '3302': '45', '3305': '45' }
>>> from itertools import groupby >>> {k:dict(g) for k,g in groupby(sorted(a.items(), key=lambda x:x[0]), key=lambda x:x[0][:2])} {'01': {'0106': '50', '0117': '35'}, '02': {'0203': '30', '0205': '30'}, '33': {'3302': '45', '3305': '45'}} |
4
wrq 2018-05-11 18:02:43 +08:00
>>> a
{'0117': '35', '0106': '50', '0205': '30', '0203': '30', '3305': '45', '3302': '45'} >>> {k[:2]: {i:j for i, j in a.items() if i.startswith(k[:2])} for k, _ in a.items()} {'02': {'0205': '30', '0203': '30'}, '33': {'3305': '45', '3302': '45'}, '01': {'0106': '50', '0117': '35'}} |
5
nullcc 2018-05-11 19:00:34 +08:00
讲真写出来以后我并不觉得优雅:
>>> groupby_res = groupby(my_dict, lambda e: e[0:2]) >>>res = dict([(mini_key, dict([(key, my_dict[key]) for key in my_dict.keys() if key.startswith(mini_key)])) for mini_key, group in groupby_res for key in group]) >>> print(res) >>> {'01': {'0106': '50', '0117': '35'}, '02': {'0203': '30', '0205': '30'}, '33': {'3302': '45', '3305': '45'}} 个人感觉最好还是写得明确一点,分多步构造也没关系。 |
6
kethylar 2018-05-11 19:32:56 +08:00
from collections import defaultdict
ret = defaultdict(dict) for k,v in a.items(): ret[k[:2]].update({k:v}) |
8
ericls 2018-05-11 23:42:13 +08:00
from itertools import group_by
b = {k: dict(v) for k, v in groupby(list(a.items()), lambda item: item[0][:2]) |
9
ericls 2018-05-11 23:43:16 +08:00
from itertools import group_by
{k: dict(v) for k, v in groupby(a.items(), lambda item: item[0][:2])} |
10
seabottom1978 2018-05-17 10:25:09 +08:00
result = {}
for i in a: if i[:2] not in result: result[i[:2]] = {i : a[i]} else: result[i[:2]][i] = a[i] |