如何合并列表中的对象

时间:2019-04-03 12:19:43

标签: python pandas

我正在用Flask设置一些rest api,我有一个具有相同名称的对象列表,但是某些字段不同,如何将具有相同名称字段的所有对象与其他对象合并?

servers_list = [{ "name": "server1", 
                  "ip": "192.168.1.1", 
                  "alias": "PRNA" }, 
                { "name": "server1", 
                  "ip": "192.168.1.2", 
                  "alias": "PRNA" }, 
                { "name": "server1", 
                  "ip": "192.168.1.1", 
                  "alias": "SLKE" }]

如您所见,有3台服务器具有相同的名称,但2台具有不同的ips和1台具有不同的别名,我希望得到一个对象:

{
  "name": "server1",
  "ip": ["192.168.1.1", "192,168.1.2"],
  "alias": ["PRNA", "SLKE"]
}

如何使用python或pandas接收它? 谢谢

5 个答案:

答案 0 :(得分:1)

这将创建新的合并字典。

servers_list = [{ "name": "server1", "ip": "192.168.1.1", "alias": "PRNA" }, { "name": "server1", "ip": "192.168.1.2", "alias": "PRNA" }, { "name": "server1", "ip": "192.168.1.1", "alias": "SLKE" }]


dict={}
for ser in servers_list:
    for key in (ser):
        if key in dict:
            if ser[key] not in dict[key]:
                dict[key].append(ser[key])
        else:
            dict[key]=[ser[key]]
print(dict)

答案 1 :(得分:0)

merged = dict()

for entry in server_list:
   if entry['name'] not in merged:
       entry['ip'] = [entry['ip']] # convert to list
       merged[entry['name']] = entry
   else: # if name is a duplicate
      merged[entry['name']]['ip'].append(entry['ip']) # add the ip

此代码合并了IP,您也可以将其扩展为别名。

答案 2 :(得分:0)

servers_list = [{ "name": "server1", "ip": "192.168.1.1", "alias": "PRNA" }, { "name": "server1", "ip": "192.168.1.2", "alias": "PRNA" }, { "name": "server1", "ip": "192.168.1.1", "alias": "SLKE" }]

import json

def loads(datas):
    ret = {}
    for i in datas:
        if isinstance(i,dict):
            for j in i.keys():
                if j in ret:
                    ret[j].add(i[j])
                else:
                    ret[j] = set( (i[j],) )
        else:
            ret[i]=None
    return ret

if __name__ == '__main__':
    t = loads(servers_list)
    for i in t.keys():
        if isinstance(t[i],set):
            t[i] = list(t[i])
    print(json.dumps(t,indent=4))

您可以迭代它们并将它们放入dict对象中。

答案 3 :(得分:0)

您可以使用列表理解和pd.concat来做到这一点:

servers_list = [{ "name": "server1", 
                  "ip": "192.168.1.1", 
                  "alias": "PRNA" }, 
                { "name": "server1", 
                  "ip": "192.168.1.2", 
                   "alias": "PRNA" }, 
                { "name": "server1", 
                  "ip": "192.168.1.1", 
                  "alias": "SLKE" }]

pd.concat([pd.DataFrame(i, index=[0]) for i in servers_list])\
  .groupby('name')\
  .agg(lambda x: x.unique().tolist())\
  .reset_index().to_dict(orient='records')

输出:

[{'name': 'server1',
  'ip': ['192.168.1.1', '192.168.1.2'],
  'alias': ['PRNA', 'SLKE']}]

答案 4 :(得分:0)

function gooseFilter(geese) {