我有以下两个表:
"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发布于 2020-05-28 23:57:29
您可以使用其他文件的相同键将文件存储在字典中:
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]}https://stackoverflow.com/questions/62068816
复制相似问题