0

I have a text file which contains

AL 28
AD 24
AT 20
BE 16
BA 20

And I want to make dictionary by this text file like

iban_lengths={}
with open('iban_lengths.txt') as fi:
    for line in fi.readlines():
        fields=line.split()
        iban_lengths[fields[0]=int(fields[1])

But I want to make same dictionary by lambda fuction in two lines, and in one lines. How can I do this?

JJJ
  • 32,902
  • 20
  • 89
  • 102

4 Answers4

2

Edit: It looks like you were going for brevity, in which case I would offer this suggestion:

iban_lengths = {a:int(b) for a,b in (r.strip().split() for r in open('iban_lengths.txt'))}

(Though no lambdas were harmed in the writing of this code, it still remains quite terse.)

gyre
  • 16,369
  • 3
  • 37
  • 47
2

Solution using lambda:

with open('iban_lengths.txt') as fi:
    iban_lengths = {line.split()[0]: (lambda line: line.split()[1])(line) for line in fi.readlines()}
print(iban_lengths)
JkShaw
  • 1,927
  • 2
  • 13
  • 14
0

If you want a Pythonic way, you can try to use dict comprehension, split the line and generate the dictionary:

print({i.split()[0]:int(i.split()[1].strip('\n')) for i in list(open('ooo.json'))})

Output:

{'BE': 16, 'AT': 20, 'BA': 20, 'AL': 28, 'AD': 24}
McGrady
  • 10,869
  • 13
  • 47
  • 69
0

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

Graham
  • 7,431
  • 18
  • 59
  • 84
dreftymac
  • 31,404
  • 26
  • 119
  • 182