python-3.x 如何从字典列表和字典列表中匹配2个条目?

q8l4jmvw  于 2023-01-22  发布在  Python
关注(0)|答案(2)|浏览(182)

我有两个目标:字典列表:

object1 = [{'samplekey', 'samplevalue'}, {'samplekey1', 'samplevalue1'}, {'samplekey2', 'samplevalue2'},]

和不同对象的列表:

object2 = [["samplekey", "samplevalue", { "connection": "Direct"}],["samplekey1", "samplevalue1",{ "connection": "Cross"}]]

我的任务是在object2中为每个object1找到正确的匹配并获得连接值。如何找到它们?
我尝试了for循环和if语句的不同变体,但没有任何效果

rt4zxlrg

rt4zxlrg1#

您可以将object2中每个项目的前2个元素转换为set,如果需要不同的长度,请使用len(o1)

object1 = [
    {'samplekey', 'samplevalue'},
    {'samplekey1', 'samplevalue1'},
    {'samplekey2', 'samplevalue2'},
    {'samplekey3', 'samplevalue3', 'samplevalue3'},
]
object2 = [["samplekey", "samplevalue", {
    "connection": "Direct"
}], ["samplekey1", "samplevalue1", {
    "connection": "Cross"
}], ["samplekey3", "samplevalue3", "samplevalue3", {
    "connection": "33333"
}]]

for o1 in object1:
    for o2 in object2:
        if set(o2[:(len(o1))]) == o1:
            print(o2[-1]['connection'])

输出:

Direct
Cross
mcdcgff0

mcdcgff02#

您可以使用嵌套的for循环来查找匹配的对象并获取连接值。外部循环将遍历object1的元素,内部循环将遍历object2的元素。对于object1中的每个元素,您可以使用“if”语句来检查“samplekey”值是否与object2中某个元素的第一个元素匹配。如果找到匹配项,可以从object2中匹配元素的嵌套字典中检索连接值。下面是代码示例:

object1 = [{'samplekey': 'samplevalue'}, {'samplekey1': 'samplevalue1'}, {'samplekey2': 'samplevalue2'},]
object2 = [["samplekey", "samplevalue", { "connection": "Direct"}],["samplekey1", "samplevalue1",{ "connection": "Cross"}]]
for obj1 in object1:
    key = list(obj1.keys())[0]
    val = list(obj1.values())[0]
    for obj2 in object2:
        if key == obj2[0] and val == obj2[1] :
            connection = obj2[2]['connection']
            print(connection)

值得注意的是,由于第一个对象是集合列表而不是字典列表,因此问题的表述有点模糊,但是不管怎样,上面的代码都应该可以工作。

相关问题