简体   繁体   English

如何将两个字典列表与 python 中的列表合并?

[英]How do I merge two lists of dicts with list of list in python?

how can I define a function如何定义 function

def join_data(data_1, data_2):
    
    #code
    
    return joined_data

where在哪里

data_1 = [{'paths': [[1,2,3]],  'pos': 1}, {'paths': [[1,2,3]], 'pos': 2},]

data_2 = [{'paths': [[6,7,8]],  'pos': 1}, {'paths': [[4,5,6]], 'pos': 2},]

The function should join paths into the same list by detecting if pos (always have 1 value) from the two data are the same, such that the output is function 应通过检测两个数据中的 pos(始终为 1 值)是否相同,将路径加入同一个列表,这样 output 是

joined_data = [{'paths': [[1,2,3][6,7,8]],  'pos': 1}, {'paths': [[1,2,3][4,5,6]], 'pos': 2},]

I apologize if I am not clear in any way, and thank you for the help.如果我有任何不清楚的地方,我深表歉意,并感谢您的帮助。

You can use an intermediate dictionary with the value of the 'pos' key as its key and merge the 'path' lists of the pos's dictionaries as value.您可以使用以“pos”键的值作为其键的中间字典,并将 pos 字典的“路径”列表合并为值。 Then build your list bay reforming dictionaries from the items of the intermediate dictionary:然后从中间字典的项目中构建您的列表海湾重组字典:

data_1 = [{'paths': [[1,2,3]],  'pos': 1}, {'paths': [[1,2,3]], 'pos': 2},]

data_2 = [{'paths': [[6,7,8]],  'pos': 1}, {'paths': [[4,5,6]], 'pos': 2},]

merged = dict()
for d in data_1 + data_2:
    merged.setdefault(d['pos'],[]).extend(d['paths']) 
merged = [ {'paths':v, 'pos':p} for p,v in merged.items() ]

print(merged)
[{'paths': [[1, 2, 3], [6, 7, 8]], 'pos': 1}, 
 {'paths': [[1, 2, 3], [4, 5, 6]], 'pos': 2}]

Use the following function;使用以下function;

def join_data(data_1, data_2):
    joined_data = []
    for i in data_1:
      for j in data_2:
        if (i['pos'] == j['pos']):
          joined_data.append({'paths': [i['paths'], j['paths']], 'pos': j['pos']})
    return joined_data

Output: Output:

[{'paths': [[[1, 2, 3]], [[6, 7, 8]]], 'pos': 1},
 {'paths': [[[1, 2, 3]], [[4, 5, 6]]], 'pos': 2}]

A function which appends from one list into the other could be like this:从一个列表附加到另一个列表的 function 可能是这样的:

def join_data(data_1, data_2):
    joined_data = data_1.copy()
    for dic in data_2:
        pos = dic['pos']
        path_items = dic['paths']
        for d in joined_data:
            if d['pos'] == pos:
                d['paths'].extend(path_items)
    return joined_data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM