【发布时间】:2019-10-03 13:55:31
【问题描述】:
昨天我遇到了一个关于在这里重新构建字典列表的问题(我提到它以防其他人遇到类似问题):
Re-structuring a list of Python Dicts using setdefault
但是,我省略了数据的一个(现在看似关键的)部分。最初我认为稍后添加额外的字典键会很容易,但事实证明这在结构上很麻烦。因此,我想出了以下方法来接近我的要求。
本质上,我希望将 2 个键 'selection_id' 和 'other_data' 上移一级并完全替换 'market_data' 字典(参见下面的理想数据结构)。
我认为我可以找到一种使用 setattr 的方法,但这在循环中使用嵌套字典似乎存在问题。此外,我什至不确定这是一种合适的方式,因为无论如何我都会预先收到所有数据,只是格式错误。
我的示例代码如下所示:
market=[{'selection_id': 1099,'value':'11', 'value_name': 'a', 'other_data': 89},
{'selection_id': 1099,'value':'78', 'value_name': 'p', 'other_data': 89},
{'selection_id': 1097,'value':'39', 'value_name': 'b', 'other_data': 89},
{'selection_id': 1097,'value':'52', 'value_name': 'f', 'other_data': 89},
{'selection_id': 1098,'value':'98', 'value_name': 'd', 'other_data': 89},
{'selection_id': 1099,'value':'13', 'value_name': 'y', 'other_data': 89},
{'selection_id': 1098,'value':'4', 'value_name': 'r', 'other_data': 89},
]
new_structure = {}
new_structure2 = []
for z in market:
new_structure.setdefault((z['selection_id'], z['other_data']), []).append({'value': z['value'], 'value_name': z['value_name']})
new_structure2.append([{'market_data': m, 'value_dict': n} for m, n in new_structure.items()])
for s in new_structure2:
for t in s:
dict = {}
dict['selection_id'] = t['market_data'][0]
dict['other_data'] = t['market_data'][1]
t['market_data'] = dict
print(new_structure2)
上面的代码产生以下内容:
[[{'market_data':
{'selection_id': 1099, 'other_data': 89}, 'value_dict':
[{'value': '11', 'value_name': 'a'}, {'value': '78', 'value_name': 'p'}, {'value': '13', 'value_name': 'y'}]},
{'market_data':
{'selection_id': 1097, 'other_data': 89}, 'value_dict':
[{'value': '39', 'value_name': 'b'}, {'value': '52', 'value_name': 'f'}]}, {'market_data':
{'selection_id': 1098, 'other_data': 89}, 'value_dict':
[{'value': '98', 'value_name': 'd'}, {'value': '4', 'value_name': 'r'}]}]]
而我正在寻找的是:
[{'selection_id': 1099, 'other_data': 89, 'value_dict':
[{'value': '11', 'value_name': 'a'}, {'value': '78', 'value_name': 'p'}, {'value': '13', 'value_name': 'y'}]},
{'selection_id': 1097, 'other_data': 89, 'value_dict':
[{'value': '39', 'value_name': 'b'}, {'value': '52', 'value_name': 'f'}]},
{'selection_id': 1098, 'other_data': 89, 'value_dict':
[{'value': '98', 'value_name': 'd'}, {'value': '4', 'value_name': 'r'}]}]
为免生疑问,对于任何给定的 'selection_id','other_data' 将始终相同,即如果有 2 个 'selection_id' = 1099 的实例,则这些的 'other_data' 将始终等于 89(在示例中它们都是 89,但实际上对于不同的 selection_id 可能会有所不同。
【问题讨论】:
标签: python arrays list dictionary nested