python-3:对象名称为字符串

问题描述 投票:0回答:1

我有以下两个表:

“ table1”:

a x1
b y1

“ table2”:

a x2
b y2

我想打开它们并创建以下字典:

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

为此,我目前正在执行以下操作:

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'}}

我的问题是,如何链接已打开表的名称,例如table1,到字典键字符串“ table1”?

类似这样(不正确):

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
python python-3.x string object
1个回答
0
投票

您可以使用彼此相同的键将文件存储在字典中:

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]}
© www.soinside.com 2019 - 2024. All rights reserved.