title: Python: Creating a dictionary using list comprehension from a list using lambda
body: <p>Conceptually, here is what I want to do:</p>
  
  <pre><code>lookup = {'A': 'aaa', 'B': 'bbb', 'C': 'ccc'}
  keys = ['A', 'B', 'Z'] # Note 'Z' does not exist in dict
  result = {}
  for key in keys:
      if key in lookup:
          result[key] = lookup[key]
      else:
          result[key] = None
  </code></pre>
  
  <p>The above code yields the following, i.e.</p>
  
  <pre><code># result == {'A': 'aaa', 'Z': None, 'B': 'bbb'}
  </code></pre>
  
  <p>Based on the advise in <a href="https://stackoverflow.com/questions/1747817/create-a-dictionary-with-list-comprehension-in-python">this post about dictionary comprehension syntax</a> I am able to do the following using v2.6 syntax:</p>
  
  <pre><code>result = dict((lambda x: (x, lookup[x]) if x in lookup else (x, None))(key) for key in keys)
  </code></pre>
  
  <p>Which works and produces same results.</p>
  
  <p>However, I was hoping that I would be able to do the following in v2.7 style (also mentioned in the above post).  But that does not seem to work,</p>
  
  <pre><code>result = { (lambda x: x: a_dict[x] if x in a_dict else x: None)(key) for key in a_list }
  </code></pre>
  
  <p>I seem to be running afoul of use of <code>:</code> in lambda with that in denoting a key.  I have also reviewed the examples given in the <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow noreferrer">original PEP</a>, too.  They don't provide any guidance, either.  Below is the output from command line:</p>
  
  <pre><code>&gt;&gt;&gt; result = { (lambda x: x : a_dict[x] if x in a_dict else x: None)(key) for key in a_list }
    File "&lt;stdin&gt;", line 1
      result = { (lambda x: x : a_dict[x] if x in a_dict else x: None)(key) for key in a_list }
                              ^
  SyntaxError: invalid syntax
  </code></pre>
  
  <p>What am I doing wrong?  Is it possible to do what I am trying to do, i.e. use v2.7 syntax of dictionary comprehension with lambda?</p>
  
  <p>Please note that I ask this <em>only</em> out of curiosity; it's not that I have a compulsion to write such production code, one that would require an expert to understand!</p>
  
  <p>PS: I should mention two other related posts that I found helpful while trying do this.  First is about <a href="https://stackoverflow.com/questions/6076270/python-lambda-function-in-list-comprehensions">using lambda in list comprehension.</a>  And another is <a href="https://stackoverflow.com/questions/33061013/python-creating-a-dictionary-using-list">creating a dictionary using list</a>.</p>