1

I have the following two tables:

"table1":

a x1
b y1

"table2":

a x2
b y2

I want to open them and create the following dictionary:

{"table1": {"a": ["x1"]}, {"b": ["y1"]}, \
 "table2": {"a": ["x2"]}, {"b": ["y2"]}}

To do so, I am currently doing the following:

with open("table1", "r") as table1, \
    open("table2", "r") as table2:

    dictionary = {"table1": {}, \
                "table2": {}}

    for line in table1:

        col1 = line.split(" ")[0]
        col2 = line.split(" ")[1].strip()

        dictionary["table1"][col1] = col2

    for line in table2:

        col1 = line.split(" ")[0]
        col2 = line.split(" ")[1].strip()

        dictionary["table2"][col1] = col2

print(dictionary)

{'table1': {'a': 'x1', 'b': 'y1'}, 'table2': {'a': 'x2', 'b': 'y2'}}

My question is, how can I link the name of the opened table, e.g. table1, to the dictionary key string "table1"?

Something like this (not correct):

with open("table1", "r") as table1, \
    open("table2", "r") as table2:

    dictionary = dict()

    for table in [table1, table2]:

        for line in table: 

            col1 = line.split(" ")[0]
            col2 = line.split(" ")[1].strip()

            dictionary[table][col1] = col2    # HERE I WANT table TO BE "table1", NOT THE OBJECT table1
0

1 Answer 1

2

You can store the files in a dictionary with the same keys of the other:

table = dict()
with open("table1", "r") as table['table1'], \
    open("table2", "r") as table['table2']:

    dictionary = dict()

    for table_name in ['table1', 'table2']:

        for line in table[table_name]: 

            col1 = line.split(" ")[0]
            col2 = line.split(" ")[1].strip()

            dictionary[table_name]={col1:[col2]}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.