简体   繁体   English

根据另一个字典列表更新字典值

[英]Updating dictionary values based on another list of dictionaries

I have a list of dictionaries called x in the form of我有一个名为 x 的字典列表,格式为

x = [{id:3, name:’abc’, order:’’} , {id:7, name:’cde’, order:’’},  {id:10, name:’zz’, order:’’}  ] 

I have a second list of dictionaries y in the form of我有字典 y 的第二个列表

y = [{id:3, order:4}, {id:10, order:6} ]

What I want to do is update the 'order' values in the first dictionary (x) based on the order value for the matching id in the second dictionary (y)我想要做的是根据第二个字典 (y) 中匹配 id 的顺序值更新第一个字典 (x) 中的“顺序”值

So in the example above x would look like the following after doing so:因此,在上面的示例中,x 在执行此操作后将如下所示:

 x = [{id:3, name:’abc’, order:4} , {id:7, name:’cde’, order:’’},  {id:10, name:’zz’, order:6} ]

I keep running into errors.我不断遇到错误。 Any help would be appreciated.任何帮助,将不胜感激。 I'm on python 3.8我在 python 3.8 上

Reconstruct list of dictionaries using comprehension使用理解重建字典列表
# create a map id => order
map_order = {dict_y["id"]: dict_y["order"] for dict_y in y}

# reconstruct x using a dict comprehension whereby order is the y value with default ""
x_update = [{"id": dict_x["id"], 
             "name": dict_x["name"], 
             "order": map_order.get(dict_x["id"], "")}
            for dict_x in x]


Update values without creating a new x list更新值而不创建新的x列表

It might be more efficient to update the values in x without reconstructing everything.在不重建所有内容的情况下更新x的值可能更有效。 Details likely depend on the size.细节可能取决于大小。 For small size, go for the comprehension for the sake of style.对于小尺寸,为了风格而去理解。

# create a map id => order
map_order = {dict_y["id"]: dict_y["order"] for dict_y in y}

for dict_x in x:
    if dict_x["id"] in map_order:
        dict_x["order"] = map_order[dict_x["id"]]

Pandas-based approach基于熊猫的方法

Also, since what you are describing is essentially an outer join, you could also use Pandas, which might be a more appropriate data structure when considering the big picture.此外,由于您所描述的本质上是外连接,因此您也可以使用 Pandas,在考虑大局时,这可能是更合适的数据结构。 Note that this assumes that "order" in x never contains useful information (hence the drop ).请注意,这假设x中的"order"从不包含有用信息(因此drop )。

import pandas as pd
pd.merge(pd.DataFrame(x).drop("order", axis=1), 
         pd.DataFrame(y), 
         how="outer"
        ).fillna("").to_dict("records"))

Pandas with update有更新的熊猫

... in case the order in x do contain useful information, which merely need to be updated, but which are supposed to be unchanged, in case the id is not present in y : ...如果x中的order确实包含有用的信息,这些信息只需要更新,但应该保持不变,以防y不存在id

df = pd.DataFrame(x).set_index("id")
df.update(pd.DataFrame(y).set_index("id"))
df.reset_index().to_dict("records")

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

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