1

Input:

A   a
B   b
C   c
D   d
E   e

Expected output:

A   B   C   D   E
a   b   c   d   e

Code:

dic = {}
with open(input_file, 'r') as input:
    for line in input:
        block = line.strip().split('\t')[0]
        dic[block] = line.strip().split('\t')[1]


with open(output_file, 'w') as ouput:
    for key, value in dic.items():

I want to change 'input' to 'expected output' without using pandas' transpose function. I added each string in a dictionary. So, how can I extract the 'expected output' using the dictionary?

Claudio
  • 7,474
  • 3
  • 18
  • 48
LoganLee
  • 145
  • 1
  • 10
  • Why do you think it's necessary to use a dictionary for this? Maybe the real problem is more complex but for this case you just need two lists – DarkKnight Dec 23 '21 at 09:22
  • See my late answer for complete solution using list of lists and zip() for transposing lines of text to columns. – Claudio Sep 17 '22 at 05:03

2 Answers2

0

Use zip:

TEST = [
    ['A', 'a'],
    ['B', 'b'],
    ['C', 'c'],
    ['D', 'd'],
    ['E', 'e'],
]

result = list(zip(*TEST))

The result is (pretty formatted):

[
    ('A', 'B', 'C', 'D', 'E'),
    ('a', 'b', 'c', 'd', 'e'),
]
VPfB
  • 14,927
  • 6
  • 41
  • 75
0

As already mentioned in the other answer the right tool for transposing the text will be not a dictionary but a list of lists which can then be easily transposed using Pythons zip() method.

Below the complete code for reading the data from file, transposing them using the function txt_T(txt_IN) which returns the transposed txt_OUT, and for writing txt_OUT to the output file.

With the option verbose=True you can follow the single steps required to achieve the result yourself again if you like (the output for the case in question is provided after the code).

txt_T(txt_IN, sep=3*" ", CRLF='\n')

allows to specify the separator between the table entries (e.g. change it to '\t' as used in your code) and the line end (on Windows change to CRLF='\r\n'):

mln_IN = """\
A   a
B   b
C   c
D   d
E   e"""
with open('transposeText_mln_IN.txt','w') as fw:
    fw.write(mln_IN)

# Expected output:
mln_OUT = """\
A   B   C   D   E
a   b   c   d   e"""

# Code:
def txt_T(txt_IN, sep=3*" ", CRLF='\n', verbose=False):
    verb_sep = '\n----------------\n'
    """ Transpose columns to lines in a table provided as txt_IN  e.g.:
            A   a
            B   b
            C   c
        and return txt_OUT of the transposed table  e.g.: 
            A   B   C
            a   b   c  """
    L = []
    if verbose: print(txt_IN, end=verb_sep)
    for line in txt_IN.split(CRLF):
        if verbose: print( line, line.split(sep) )
        L.append(line.split())
    if verbose: print(verb_sep[1:], end='')
    if verbose: print(L, end='\n---\n')
    if verbose: print( [ list(item) for item in zip(*L) ], end=verb_sep)
    txt_OUT = CRLF.join([sep.join(list(item)) for item in zip(*L)])
    if verbose: print(txt_OUT)
    return txt_OUT
# ---
with open('transposeText_mln_IN.txt','r') as fr:
    txt_IN  = fr.read()
    # assert txt_IN  == mln_IN  # for code test purposes
    sep = 3*" "
    CRLF='\n'
    txt_OUT = txt_T(txt_IN, sep=sep, CRLF=CRLF)
    # assert txt_OUT == mln_OUT # for code test purposes

with open('transposeText_mln_OUT.txt','w') as fw:
    fw.write(txt_OUT)

gives with verbose=True:

A   a
B   b
C   c
D   d
E   e
----------------
A   a ['A', 'a']
B   b ['B', 'b']
C   c ['C', 'c']
D   d ['D', 'd']
E   e ['E', 'e']
----------------
[['A', 'a'], ['B', 'b'], ['C', 'c'], ['D', 'd'], ['E', 'e']]
---
[['A', 'B', 'C', 'D', 'E'], ['a', 'b', 'c', 'd', 'e']]
----------------
A   B   C   D   E
a   b   c   d   e
Claudio
  • 7,474
  • 3
  • 18
  • 48