用另一个词典列表更新词典列表。有没有更快的方法?

我有一个字典列表,需要使用另一个字典列表中的信息进行更新。我当前的解决方案(如下)的工作方式是从第一个列表中取出每个词典,然后将其与第二个列表中的每个词典进行比较。它可以工作,但是有没有更快,更优雅的方法来达到相同的结果呢?


a = [ { "id": 1, "score":200 }, { "id": 2, "score":300 }, { "id":3, "score":400 } ]

b = [ { "id": 1, "newscore":500 }, { "id": 2, "newscore":600 } ]

# update a with data from b

for item in a:

    for replacement in b:

        if item["id"]==replacement["id"]:

            item.update({"score": replacement["newscore"]})


手掌心
浏览 146回答 3
3回答

有只小跳蛙

通过id使用第一个数组创建索引的字典。使用循环遍历第二个数组id。for replacement in b:   v = lookup.get(replacement['id'], None)   if v is not None:      v['score'] = replacement['newscore']这将O(n^2)问题转化为O(n)问题。

梵蒂冈之花

与其进行len(a)* len(b)循环,不如将b加工成更易于使用的东西:In [48]: replace = {d["id"]: {"score": d["newscore"]} for d in b}In [49]: new_a = [{**d, **replace.get(d['id'], {})} for d in a]In [50]: new_aOut[50]: [{'id': 1, 'score': 500}, {'id': 2, 'score': 600}, {'id': 3, 'score': 400}]请注意,该{**somedict}语法要求使用现代版本的Python(> = 3.5)。

扬帆大鱼

清单理解:[i.update({"score": x["newscore"]}) for x in b for i in a if i['id']==x['id']] print(a)输出:[{'id': 1, 'score': 500}, {'id': 2, 'score': 600}, {'id': 3, 'score': 400}]定时:%timeit [i.update({"score": x["newscore"]}) for x in b for i in a if i['id']==x['id']]输出:100000 loops, best of 3: 3.9 µs per loop
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python