如何合并3个不同的dict中的几个列表的一部分

时间:2018-01-14 22:12:33

标签: python arrays sorting merge

对于一个小项目,我必须向API请求我得到不同的结果,我需要合并这些结果的一部分," count",在同一个词典/列表中或者无论如何

我尝试了这个(并且它有效)但我确信有更好的方法,更加pythonic

预期结果:

[{'id': 109, 'descr': 'foo','counta': '110','countb': '26','countc': '72'}, 
 {'id': 114, 'descr': 'bar','counta': '810','countb': '53','countc': '42'}]

第一次请求结果:

[{'id': 109, 'descr': 'foo','count': '110'}, 
 {'id': 114, 'descr': 'bar','count': '810'}]

第二次请求结果:

[{'id': 109, 'descr': 'foo','count': '26'}, 
 {'id': 114, 'descr': 'bar','count': '53'}]

第3次请求结果:

[{'id': 109, 'descr': 'foo','count': '72'}, 
 {'id': 114, 'descr': 'bar','count': '42'}]

servers_list = []


for ida in first_request:
    for idb in second_request:
        if ida['id'] == idf['id']:
            for idc in third_request:
                if idc['id'] == ida['id']:

                    total = {'id': ida['offer_id'],
                        'descr': ida['offer_description'],
                        'a': ida['count'],
                        'b': idb['count'],
                        'c': idc['count']

                        }


    slist.append(total)

提前感谢您的帮助:)

2 个答案:

答案 0 :(得分:1)

您似乎想要使用pip install -r requirements.txt。将您的词典列表转换为数据框:

pandas

将它们加入具有冗余列的新宽数据帧:

import pandas as pd
d1 = pd.DataFrame(first_result)
d2 = ...
d3 = ...

删除重复的列:

d = d1.join(d2,rsuffix='b').join(d3,rsuffix='c')

#  count descr   id countb descrb  idb countc descrc  idc
#0   110   foo  109     26    foo  109     72    foo  109
#1   810   bar  114     53    bar  114     42    bar  114

将结果转换回字典列表:

d.drop(['idb','idc','descrb','descrc'], axis=1, inplace = True)

答案 1 :(得分:0)

解决方案,不依赖于其他模块。

# input data

results = [
[{'id': 109, 'descr': 'foo','count': '110'}, 
 {'id': 114, 'descr': 'bar','count': '810'}],
[{'id': 109, 'descr': 'foo','count': '26'}, 
 {'id': 114, 'descr': 'bar','count': '53'}],
[{'id': 109, 'descr': 'foo','count': '72'}, 
 {'id': 114, 'descr': 'bar','count': '42'}]
]

COPY_KEYS = ['id', 'descr']
MERGE_KEYS = ['count']
MERGE_SUFFIXES = [chr(o) for o in range(ord('a'), ord('z') + 1)]

# basic setup for our data structure

merged = [{} for _ in results[0]]

# copy fixed keys

# as these keys are the same for all results, just steal from the first
for i_result_row, result_row in enumerate(results[0]):
  for key in COPY_KEYS:
    merged[i_result_row][key] = result_row[key]

# copy dynamic keys

for i_result, result in enumerate(results):
  for i_result_row, result_row in enumerate(result):
    for key in MERGE_KEYS:
      merged[i_result_row][key + MERGE_SUFFIXES[i_result]] = result_row[key]

# output

print("Expected result:")
print("[{'id': 109, 'descr': 'foo', 'counta': '110', 'countb': '26', 'countc': '72'}, ")
print("{'id': 114, 'descr': 'bar', 'counta': '810', 'countb': '53', 'countc': '42'}]")

print("Actual result:")
print(str(merged).replace('}, {', '},\n{'))

作为输出,我得到了这个:

Expected result:
[{'id': 109, 'descr': 'foo', 'counta': '110', 'countb': '26', 'countc': '72'}, 
{'id': 114, 'descr': 'bar', 'counta': '810', 'countb': '53', 'countc': '42'}]
Actual result:
[{'counta': '110', 'id': 109, 'descr': 'foo', 'countc': '72', 'countb': '26'},
{'counta': '810', 'id': 114, 'descr': 'bar', 'countc': '42', 'countb': '53'}]

由于哈希,对于Python< 3.6。

,键的顺序可能会有所不同