您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python3如何通过唯一键连接两个dicts列表

5b51 2022/1/14 8:22:42 python 字数 2586 阅读 586 来源 www.jb51.cc/python

我有两个清单: list1 = [ {'sth': 13, 'important_key1': 'AA', 'important_key2': '3'}, {'oh!': 14, 'important_key1': 'FF', 'important_key2': '4'}, {'sth_else': 'abc', 'important_key1': 'ZZ', 'important_key2':

概述

list1 = [ {'sth': 13,'important_key1': 'AA','important_key2': '3'},{'oh!': 14,'important_key1': 'FF','important_key2': '4'},{'sth_else': 'abc','important_key1': 'ZZ','important_key2': '5'}]
list2 = [ {'why-not': 'tAk','important_key1': 'GG',{'hmmm': 'no','important_key2': '3'}]

我想返回一个仅包含来自list1的对象的列表,但如果同一个important_key1和important_key2在list2中的任何元素中,我想从list2中获取该元素.

所以输出应该是:

[ {'hmmm': 'no','important_key2': '5'}]

通过两个或三个循环来做它并不复杂,但我想知道是否有一种简单的方法可以使用列表推导或类似的东西.

这是“正常”的方式:

list1 = [ {'sth': 13,'important_key2': '4'}]
list2 = [ {'hmmm': 'no',{'why-not': 'tAk','important_key2': '4'}]

final_list = []
for element in list1:
    there_was_in_list2 = False
    for another_element in list2:
        if element['important_key1'] == another_element['important_key1'] and element['important_key2'] == another_element['important_key2']:
            final_list.append(another_element)
            there_was_in_list2 = True
            break
    if not there_was_in_list2:
        final_list.append(element)
print(final_list)

是否有任何Pythonic方法可以做到这一点?

keys = ['important_key1','important_key2']
d2 = {tuple(d[k] for k in keys): d for d in list2[::-1]}
print([d2.get(tuple(d[k] for k in keys),d) for d in list1])

输出(带有您的样本输入):

[{‘hmmm’:’不’,’important_key1’:’AA’,’important_key2’:’3′},{‘哦!’:14,’important_key1’:’FF’,’important_key2’:’4′ },{‘sth_else’:’abc’,’important_key1’:’ZZ’,’important_key2’:’5′}]

正如您在问题中所描述的那样,list1中只有{‘sth’:13,’important_key2’:’3′}将替换为{‘hmmm’:’no’,’important_key1’: ‘AA’,’important_key2’:’3′}因为只有这个dict的important_key1和important_key2都匹配list2中的dict.

总结

以上是编程之家为你收集整理的Python3如何通过唯一键连接两个dicts列表全部内容,希望文章能够帮你解决Python3如何通过唯一键连接两个dicts列表所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶