![](/img/trans.png)
[英]Updating values of one nested dictionary to another having list of dictionaries
[英]Updating dictionary values based on another list of dictionaries
我有一个名为 x 的字典列表,格式为
x = [{id:3, name:’abc’, order:’’} , {id:7, name:’cde’, order:’’}, {id:10, name:’zz’, order:’’} ]
我有字典 y 的第二个列表
y = [{id:3, order:4}, {id:10, order:6} ]
我想要做的是根据第二个字典 (y) 中匹配 id 的顺序值更新第一个字典 (x) 中的“顺序”值
因此,在上面的示例中,x 在执行此操作后将如下所示:
x = [{id:3, name:’abc’, order:4} , {id:7, name:’cde’, order:’’}, {id:10, name:’zz’, order:6} ]
我不断遇到错误。 任何帮助,将不胜感激。 我在 python 3.8 上
# 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]
x
列表在不重建所有内容的情况下更新x
的值可能更有效。 细节可能取决于大小。 对于小尺寸,为了风格而去理解。
# 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,在考虑大局时,这可能是更合适的数据结构。 请注意,这假设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"))
...如果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.