有没有办法在python中合并两个字典列表而不产生重复项?



我想在python中将这两个字典列表合并为一个-

输入

arr1 = [
{ "field": 'nickname', "direction": 'ASC' },
{ "field": 'email', "direction": 'ASC' },
{ "field": 'name', "direction": 'ASC' },
{ "field": 'first_name', "direction": 'ASC' }
]
arr2 = [
{ "field" : "nickname", "direction" : "DESC"},
{ "field" : "email", "direction" : "DESC"},
{ "field" : "last_name", "direction" : "DESC"}
]

,需要输出-

输出
[
{ field: "nickname",   direction: "DESC"},
{ field: "email",      direction: "DESC"},
{ field: "last_name",  direction: "DESC"},
{ field: "name",       direction: "ASC" },
{ field: "first_name", direction: "ASC" }
]

My Solution -

arr1 = [
{ "field": 'nickname', "direction": 'ASC' },
{ "field": 'email', "direction": 'ASC' },
{ "field": 'name', "direction": 'ASC' },
{ "field": 'first_name', "direction": 'ASC' }
]
arr2 = [
{ "field" : "nickname", "direction" : "DESC"},
{ "field" : "email", "direction" : "DESC"},
{ "field" : "last_name", "direction" : "DESC"}
]
arr4 = arr2;
arr3 = []
for i in range(0, len(arr1)):
for j in range(0, len(arr2)):
flag = 0
if(arr1[i]['field'] == arr2[j]['field']):
arr3.append(arr2[j])
arr4.remove(arr2[j])
flag = 1
break
if flag == 0 :
arr3.append(arr1[i])
arr3 += arr4
print(arr3)

我尝试了几种方法,但需要在不修改arr2的情况下以O(n)复杂度完成。有什么办法吗?

尝试:

out = {}
for d in arr1 + arr2:
out[d["field"]] = d["direction"]
out = [{"field": k, "direction": v} for k, v in out.items()]
print(out)

打印:

[
{"field": "nickname", "direction": "DESC"},
{"field": "email", "direction": "DESC"},
{"field": "name", "direction": "ASC"},
{"field": "first_name", "direction": "ASC"},
{"field": "last_name", "direction": "DESC"},
]

一行代码应该是pandas:

df=pd.DataFrame.from_dict(arr1).append(pd.DataFrame.from_dict(arr2)).drop_duplicates('field', keep='last').reset_index(drop=True)

,结果是:

field direction
0        name       ASC
1  first_name       ASC
2    nickname      DESC
3       email      DESC
4   last_name      DESC

算法应该很简单:

  1. 为结果创建一个新地图
  2. 决定在冲突(重复的键映射到不同的值)的情况下,每个输入Map(或Map列表)中的哪个键/值对应优先考虑
  3. 考虑顺序和优先级,在输入映射上编写迭代结构。

Q:在map列表中较早出现的map的key是否应该保留它们的值?或者地图的键应该出现在地图列表的后面?

相关内容

  • 没有找到相关文章

最新更新