首页 > 解决方案 > 将字典压缩成字典字典

问题描述

我试图通过键中的尾随数字将这些字段组合在一起,以便打开这个字典:

dict = {
'location_1': 'Living Room', 'status_1': True, 'information_1': 'good', 
'location_2': 'Dining Room', 'status_2': True, 'information_2': 'good', 
'location_3': 'Kitchen', 'status_3': True, 'information_3': 'good'
}

进入这个:

new = {
'Living Room': {'status': True, 'information': 'good'},
'Dining Room': {'status': True, 'information': 'good'}, 
'Kitchen': {'status': True, 'information': 'good'}
}

我怎样才能做到这一点?

这是我的尝试,我似乎无法正确理解逻辑:

        json = dict()
        counter = 0
        so_far = {}
        for key, value in cleaned_data.items():
            v = key.split('_')[0]
            print(v)
            so_far[key.split('_')[0]] = value
            print(so_far)
            if counter != 0 and counter % 3 == 0:
                # I don't know where status or information are yet...
                json[so_far['location']] = {
                    'status': so_far['status'],
                    'information': so_far['information']
                }
                # reset
                so_far = dict()
            counter += 1
        print(json)

标签: pythonpython-3.xdictionary

解决方案


您可以使用itertools.groupby

from itertools import groupby
d = {'location_1': 'Living Room', 'status_1': True, 'information_1': 'good', 'location_2': 'Dining Room', 'status_2': True, 'information_2': 'good', 'location_3': 'Kitchen', 'status_3': True, 'information_3': 'good'}
new_d = [(a.split('_'), b) for a, b in d.items()]
new_data = [{c:d for [c, _], d in b} for _, b in groupby(sorted(new_d, key=lambda x:x[0][1]), key=lambda x:x[0][1])]
result = {i['location']:{'status':i['status'], 'information':i['information']} for i in new_data}

输出:

{'Living Room': {'status': True, 'information': 'good'}, 'Dining Room': {'status': True, 'information': 'good'}, 'Kitchen': {'status': True, 'information': 'good'}}

编辑:如果最终输出中的不同信息值是故意的,您可以使用zip

info = ['good', 'awesome', 'yay']
result = {i['location']:{'status':i['status'], 'information':a} for i, a in zip(new_data, info)}

输出:

{'Living Room': {'status': True, 'information': 'good'}, 'Dining Room': {'status': True, 'information': 'awesome'}, 'Kitchen': {'status': True, 'information': 'yay'}}

推荐阅读