我有一个包含多个JSON行的字典,如下所示。
my_dict = [{'processId': 'p1', 'userId': 'user1', 'reportName': 'report1', 'threadId': '12234', 'some_other_keys': 'respective values.12234'}, {'userId': 'user1', 'processId': 'p1', 'reportName': 'report1', 'threadId': '12335', 'some_other_keys': 'respective values.12335', 'another_key': 'another_value.12335','key1': 'key1_value.12335'}, {'processId': 'p1', 'userId': 'user1', 'reportName': 'report1', 'threadId': '12834', 'some_other_keys': 'respective values.12834','key2': 'key2_value.12834'}]注意:不同的json行有不同的键集。
在这些行中,'processId':'p1','userId':‘user1 1’,'reportName':'report1‘对于所有行都是相同的,这是程序员所知道的。
目标:
above.
["processId","userId","reportName"]输出:
上述输入字典的expect输出如下所示,这是一个JSON记录。
{"processId": "p1", "userId": "user1", "reportName": "report1", "threadId_0": "12234", "some_other_keys_0": "respective values.12234", "threadId_1": "12335", "some_other_keys_1": "respective values.12335", "another_key_1": "another_value.12335","key1_1": "key1_value.12335", "threadId_2": "12834", "some_other_keys_2": "respective values.12834","key2_2": "key2_value.12834"}我的当前代码如下所示:
def multijson_to_singlejson_matchingkey(list_json, list_keys):
rec0 = {}
for l in range(len(list_keys)):
key0 = list_keys[l]
value0 = list_json[0][key0]
rec0[f'{key0}'] = value0
rec = {}
for i in range(len(list_json)):
line = list_json[i]
for j in range(len(list_keys)):
del line[list_keys[j]]
line_keys = list(line)
for k in range(len(line_keys)):
key_a = line_keys[k] + "_" + f"{i}"
line[f'{key_a}'] = line[f'{line_keys[k]}']
del line[f'{line_keys[k]}']
rec = {**rec, **line}
res = {}
res = {**rec0, **rec}
print(res)
return res但这是一个有20行代码的函数。我试图用较少的代码行来优化代码,并使其性能更高效。需要帮助,在可用的选项,以这样做。
发布于 2020-08-24 18:08:12
您可以将rec0的生成简化为一个有希望具有合理可读性的一行,然后遍历输入字典列表以填充其余的内容,忽略list_keys中的任何键(尽管在这里对rec0进行了相当的测试,因为它的速度稍微快一些):
def multi_to_single(list_json, list_keys):
rec0 = dict((key0, list_json[0][key0]) for key0 in list_keys)
res = rec0.copy()
for i, dct in enumerate(list_json):
for k, v in dct.items():
if k not in rec0:
res[f'{k}_{i}'] = v
print(res)
return res这提供了(这里使用的是pprint.pprint,而不是print,以便于阅读):
{'another_key_1': 'another_value.12335',
'key1_1': 'key1_value.12335',
'key2_2': 'key2_value.12834',
'processId': 'p1',
'reportName': 'report1',
'some_other_keys_0': 'respective values.12234',
'some_other_keys_1': 'respective values.12335',
'some_other_keys_2': 'respective values.12834',
'threadId_0': '12234',
'threadId_1': '12335',
'threadId_2': '12834',
'userId': 'user1'}https://stackoverflow.com/questions/63566178
复制相似问题