2016-02-28 30 views
2

我有两个字典列表,例如,获取列表中字典的键值对位于另一个字典列表中

L1 = [ 
    {'ID': '1', 'file': 'test1', 'ext': 'txt'}, 
    {'ID': '2', 'file': 'test2', 'ext': 'txt'}, 
    {'ID': '3', 'file': 'test3', 'ext': 'py'} 
] 

L2 = [ 
    {'file': 'test1', 'ext': 'txt', 'val': '5'}, 
    {'file': 'test3', 'ext': 'py', 'val': '7'}, 
    {'file': 'test4', 'ext': 'py', 'val': '8'} 
] 

我想从L1提取所有字典,其中的关键在于:的'file''ext'值对可以在L2字典中找到。

在我们的例子

L = [ 
    {'ID': '1', 'ext': 'txt', 'file': 'test1'}, 
    {'ID': '3', 'ext': 'py', 'file': 'test3'} 
] 

有一个聪明的Python的方式做到这一点?

+0

那你试试这么远吗? –

回答

1

使用您的输入:

L1 = [ 
    {'ID': '1', 'file': 'test1', 'ext': 'txt'}, 
    {'ID': '2', 'file': 'test2', 'ext': 'txt'}, 
    {'ID': '3', 'file': 'test3', 'ext': 'py'} 
] 

L2 = [ 
    {'file': 'test1', 'ext': 'txt', 'val': '5'}, 
    {'file': 'test3', 'ext': 'py', 'val': '7'}, 
    {'file': 'test4', 'ext': 'py', 'val': '8'} 
] 

您可以提取file - 一组第一ext双:

pairs = {(d['file'], d['ext']) for d in L2 for k in d} 

和过滤器他们在第二个步骤:

[d for d in L1 if (d['file'], d['ext']) in pairs] 

结果:

[{'ID': '1', 'ext': 'txt', 'file': 'test1'}, 
{'ID': '3', 'ext': 'py', 'file': 'test3'}] 
4

您可以使用下面的列表理解:

L1 = [ 
    {'ID':'1','file':'test1','ext':'txt'}, 
    {'ID':'2','file':'test2','ext':'txt'}, 
    {'ID':'3','file':'test3','ext':'py'} 
] 

L2 = [ 
    {'file':'test1','ext':'txt','val':'5'}, 
    {'file':'test3','ext':'py','val':'7'}, 
    {'file':'test4','ext':'py','val':'8'} 
] 


L = [d1 for d1 in L1 if any(
     d2.get('file') == d1['file'] and d2.get('ext') == d1['ext'] for d2 in L2)] 
print(L) 

输出

[{'ID': '1', 'ext': 'txt', 'file': 'test1'}, 
{'ID': '3', 'ext': 'py', 'file': 'test3'}] 

这遍历每个字典d1L1,并为每一个测试,如果这两个键:值对和d1['ext']存在于L2的任何字典中。

2

这是一个通用函数(健壮),它将接受匹配关键参数。

def extract_matching_dictionaries(l1, l2, mk): 
    return [d1 for d1 in l1 if all(k in d1 for k in mk) and 
      any(all(d1[k] == d2[k] for k in mk) for d2 in l2 if all(k in d2 for k in mk))] 

例子:

>>> extract_matching_dictionaries(L1, L2, ['file', 'ext']) 
[{'ID': '1', 'ext': 'txt', 'file': 'test1'}, 
{'ID': '3', 'ext': 'py', 'file': 'test3'}] 
1
#!/usr/bin/python 
# -*- coding: utf-8 -*- 

L1 = [{'ID': '1', 'file': 'test1', 'ext': 'txt'}, {'ID': '2', 
     'file': 'test2', 'ext': 'txt'}, {'ID': '3', 'file': 'test3', 
     'ext': 'py'}] 

L2 = [{'file': 'test1', 'ext': 'txt', 'val': '5'}, {'file': 'test3', 
     'ext': 'py', 'val': '7'}, {'file': 'test4', 'ext': 'py', 
     'val': '8'}] 

keys = ['file', 'ext'] 

for each in L1: 
    for each1 in L2: 
     if each1[keys[0]] == each[keys[0]] and each1[keys[1]] \ 
== each[keys[1]]: 
      print each 
+0

如果你只是通过索引明确使用它们,'keys'列表的要点是什么? –

相关问题