python - 将字典压缩成字典字典
问题描述
我试图通过键中的尾随数字将这些字段组合在一起,以便打开这个字典:
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)
解决方案
您可以使用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'}}
推荐阅读
- javascript - 不理解 async.parallel() 中的内部回调
- regex - 正则表达式获取特定文本集之后的 [nth] 名称
- c - 使用 OpenMP 并行化循环时的循环依赖
- javascript - 具有多个 div 内容的 PHP XMLHTTP Jquery
- android - Android Room 数据库设计的最佳实践:使用多个类/接口或多个查询
- reactjs - 添加曲目或创建以 Media Recorder 结尾的新流结束损坏的文件
- python - 正方形和立方体表
- javascript - 如何使用 Ajax 将 MultiDict 查询从 MultiSelect 发布到 Flask?
- python - TypeError:类型“types.GenericAlias”不是可接受的基本类型
- asynchronous - 设计问题回复:异步 firestore 查询不适用于 firestore 自动对象刷新