首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python-3:字符串形式的对象名称

python-3:字符串形式的对象名称
EN

Stack Overflow用户
提问于 2020-05-28 23:43:44
回答 1查看 44关注 0票数 1

我有以下两个表:

"table1":

代码语言:javascript
复制
a x1
b y1

"table2":

代码语言:javascript
复制
a x2
b y2

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

代码语言:javascript
复制
{"table1": {"a": ["x1"]}, {"b": ["y1"]}, \
 "table2": {"a": ["x2"]}, {"b": ["y2"]}}

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

代码语言:javascript
复制
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?

如下所示(不正确):

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-28 23:57:29

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

代码语言:javascript
复制
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]}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62068816

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档