简体   繁体   中英

List of 2-tuples from 2 lists of dictionaries based on value of keys in python

I have two lists of dictionaries lx and ly . Elements of lx contains a key of interest key1 and those of ly contain key2 . I want to create a list of 2-tuples (a,b) where a is a dictionary from lx and b is a dictionary from ly such that the a['key1'] == b['key2'] . Is there a way to do this directly with a list comprehension?

My failed attempt is:

out = [(a,b) for a in lx for b in ly and a['key1'] == b['key2']]

but I am getting a 'local variable b referenced before assignment' error.

UPDATE:

An example input would be:

lx = [{'key1': 'a', 'xyz': 1}, 
      {'key1': 'b', 'xyz': 2}, 
      {'key1': 'c', 'xyz': 3}]

ly = [{'key2': 'a', 'abc': '66'}, 
      {'key2': 'c', 'abc': '01'}]

output:

out = [({'key1': 'a', 'xyz': 1}, {'key2': 'a', 'abc': '66'}), 
       ({'key1': 'c', 'xyz': 3}, {'key2': 'c', 'abc': '01'})]

You need to use if before the condition instead of and :

>>> lx = [{'key1': 'foo'},  {'key1': 'foobar'}]
>>> ly = [{'key2': 'foo'},  {'key2': 'bar'}]
>>> [(a,b) for a in lx for b in ly and a['key1'] == b['key2']]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
UnboundLocalError: local variable 'b' referenced before assignment
>>> [(a,b) for a in lx for b in ly if a['key1'] == b['key2']]
[({'key1': 'foo'}, {'key2': 'foo'})]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM