Quick Answer (TL;DR)
## barebones-simple-example -- dictionary comprehension
mydict = {ixx: ixx**2 for ixx in range(6) if(ixx > 1)}
## ^ ^ ^ ^
## | | | |
## key value rawdata filter condition
##
## result --> {2: 4, 3: 9, 4: 16, 5: 25}
Detailed Answer
Context
- Python 2.7+
- Python 3.x
- Creating a "one-liner" style program that can be entered from the commandline
- Iterating over raw input data to create a dictionary data structure (aka associative-array)
Problem
- Scenario: Developer PyjooParkLift wishes to create the fewest-number-of-lines program to transform rawdata input to a python dictionary.
Details
The question presented here seems to mix two different questions:
- Q1) How to create a "one-liner" style program in python to carry out a general-purpose task
- Q2) Which specific language constructs are best suited to get the task done
Although python lambda functions do provide a concise syntax, it is not necessary to use them in order to meet the goal of Question 1.
If the only goal is to create concise source code (such as for use on a bash command-prompt for example) there is no general reason why a lambda function has to be used at all.
Solution
by analogy ...
## this program using lambda ...
mydict = {ixx: (lambda ixx: ixx**2)(ixx) for ixx in range(6)}
## ... produces the same result as this one without using lambda
mydict = {ixx: ixx**2 for ixx in range(6) if(ixx > 1)}
Pitfalls
- In constructing content from rawdata input file:
- make sure the input data are normalized and in the format you expect
- make sure the security context is well-defined and you are not misusing potentially untrusted input
- make sure to account for routine IO issues, such as filesize constraints and blank lines
See also