简体   繁体   English

将列表列表的值与字典列表合并

[英]merge values of list of lists with a list of dictionaries

u= [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '10']]
v=[{'id': 'a', 'adj': ['blue', 'yellow']}, {'id': 'b', 'adj': ['purple', 'red']}, {'id': 'c', 'adj': ['green', 'orange']}, {'id': 'd', 'adj': ['black', 'purple']}]

I want: 我想要:

 result=[ {'id': 'a', 'adj': ['blue', 'yellow'], 'value': '1' },
        {'id': 'a', 'adj': ['blue', 'yellow'], 'value': '2' },
        {'id': 'a', 'adj': ['purple', 'red'], 'value': '3' },
        ...]

I've converted u to a dictionary: 我已经转换u字典:

m=[]
for i in u:
    s={}
    s['value']=i
    m.append(s)

#>>m= [{'value': ['1', '2']}, {'value': ['3']}, {'value': ['4', '5', '6']}, {'value': ['7', '8', '9', '10']}]

Then tried to applied zip function... 然后尝试应用zip功能...

for i,j in enumerate(v):
    for s,t in enumerate(l):
        if i= =s:
            #zip 2 dictionary together. Stuck here

Thanks a lot in advance! 在此先多谢! This is my 2nd week of learning programming. 这是我学习编程的第二周。

You need to zip, iterate over each sublist from u, deepcopy each dict from v and add the new key/value pairing, finally append the new dict to a list: 您需要压缩,从u遍历每个子列表,从v 深度复制每个字典并添加新的键/值对,最后将新字典追加到列表中:

from copy import deepcopy

u= [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '10']]
v=[{'id': 'a', 'adj': ['blue', 'yellow']}, {'id': 'b', 'adj': ['purple', 'red']}, {'id': 'c', 'adj': ['green', 'orange']}, {'id': 'd', 'adj': ['black', 'purple']}]

out = []
# match up corresponding elements fromm both lists
for dct, sub in zip(v, u):
    # iterate over each sublist
    for val in sub:
        # deepcopy the dict as it contains mutable elements (lists)
        dct_copy = deepcopy(dct)
        # set the new key/value pairing
        dct_copy["value"] = val
        # append the dict to our out list
        out.append(dct_copy)
from pprint import pprint as pp
pp(out)

Which will give you: 这会给你:

[{'adj': ['blue', 'yellow'], 'id': 'a', 'value': '1'},
 {'adj': ['blue', 'yellow'], 'id': 'a', 'value': '2'},
 {'adj': ['purple', 'red'], 'id': 'b', 'value': '3'},
 {'adj': ['green', 'orange'], 'id': 'c', 'value': '4'},
 {'adj': ['green', 'orange'], 'id': 'c', 'value': '5'},
 {'adj': ['green', 'orange'], 'id': 'c', 'value': '6'},
 {'adj': ['black', 'purple'], 'id': 'd', 'value': '7'},
 {'adj': ['black', 'purple'], 'id': 'd', 'value': '8'},
 {'adj': ['black', 'purple'], 'id': 'd', 'value': '9'},
 {'adj': ['black', 'purple'], 'id': 'd', 'value': '10'}]

dicts have a .copy attribute or you could call dict(dct) but because you have mutable object as values, just doing a shallow copy will not work. .copy具有.copy属性,或者您可以调用dict(dct)但是由于您具有可变对象作为值,因此仅执行浅表复制将不起作用。 The example below shows you the actual difference: 下面的示例向您显示实际差异:

In [19]: d = {"foo":[1, 2, 4]}

In [20]: d1_copy = d.copy() # shallow copy, same as dict(d)

In [21]: from copy import  deepcopy

In [22]: d2_copy = deepcopy(d) # deep copy

In [23]: d["foo"].append("bar")

In [24]: d
Out[24]: {'foo': [1, 2, 4, 'bar']}

In [25]: d1_copy
Out[25]: {'foo': [1, 2, 4, 'bar']} # copy also changed

In [26]: d2_copy
Out[26]: {'foo': [1, 2, 4]} # deepcopy is still the same

what-exactly-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignment 什么-恰好是最差之间,浅拷贝deepcopy的和正常的赋值

Apply zip on both lists, and create a new dictionary where the old ones have the values from the corresponding list added as the key-value entry value : number from list : 在两个列表上都应用zip ,并创建一个新字典,其中旧字典将对应列表中的值添加为键值输入valuelist中的数字

>>> import pprint, copy
>>> result = [dict(copy.deepcopy(j), value = ind) for i, j in zip(u, v) for ind in i]
>>> pprint.pprint(result)
[{'adj': ['blue', 'yellow'], 'id': 'a', 'value': '1'},
 {'adj': ['blue', 'yellow'], 'id': 'a', 'value': '2'},
 {'adj': ['purple', 'red'], 'id': 'b', 'value': '3'},
 {'adj': ['green', 'orange'], 'id': 'c', 'value': '4'},
 {'adj': ['green', 'orange'], 'id': 'c', 'value': '5'},
 {'adj': ['green', 'orange'], 'id': 'c', 'value': '6'},
 {'adj': ['black', 'purple'], 'id': 'd', 'value': '7'},
 {'adj': ['black', 'purple'], 'id': 'd', 'value': '8'},
 {'adj': ['black', 'purple'], 'id': 'd', 'value': '9'},
 {'adj': ['black', 'purple'], 'id': 'd', 'value': '10'}]

You can use the following code to acquire the desired result. 您可以使用以下代码获取所需的结果。

result = []
for index, d in enumerate(u):
    for value in d:
        result.append(dict(v[index], value=value))

It iterates over an enumerate -ion of u , and then appends a combination of the correct v dict and the value to the result list. 它遍历一个enumerate的-离子u ,然后追加正确的组合v字典和valueresult列表中。

You can compress this into a relatively clean one-liner using a list comprehension. 您可以使用列表推导将其压缩为相对干净的单行代码。

result = [dict(v[index], value=value) for index, d in enumerate(u) for value in d]

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

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