我有两个主要词典:
dict_main1 = {}
dict_main2 = {}
然后我打开许多字典(我只有26个中的6个以下),这些字典根据一个特定的字符串存储主要字典的值:
string1 = {}
string2 = {}
string3 = {}
string4 = {}
string5 = {}
string6 = {}
for key, value in dict_main1.items():
if 'string1' in key:
string1[key] = dict_main1[key]
elif 'string2' in key:
string2[key] = dict_main1[key]
elif 'string3' in key:
string3[key] = dict_main1[key]
......
for key, value in dict_main2.items():
if 'string4' in key:
string4[key] = dict_main2[key]
elif 'string5' in key:
string5[key] = dict_main2[key]
elif 'string6' in key:
string6[key] = dict_main2[key]
......
如何以Python方式为每个strin#= {}打开文件?我想避免一个接一个地做(如下例所示):
FI = open ('string1', w)
for key, value in string1.items():
OUT = key + '\n' + value + '\n'
FI.write(OUT)
答案 0 :(得分:2)
首先,您不需要99999格,只需使用其中带有格的格。
例如:
from collections import collections.defaultdict
my_keys = ['str1', 'str2', ....]
container_dict = defaultdict(dict)
for key, value in dict_main.items():
for k in my_keys:
if k in key:
container_dict[k][key] = value
现在查看文件,仅用于:
for string, strings_dict in container_dict:
with open(string, "wb") as f:
# format string dict... and save it
我没有运行这段代码,所以也许有一些错误,但是我想还可以
答案 1 :(得分:1)
使用单个词典数据结构而不是维护26个不同的词典可能会有用。
def split_dict(d, corpus):
dicts = {{} for w in corpus}
for k, v in d.items():
word = next(filter(lambda w: w in k, corpus))
dicts[word][k] = v
return dicts
dict_main = {...}
corpus = [f'string{i}' for i in range(1, 4)]
dict_split = split_dict(dict_main, corpus)
现在,只需遍历dict_split
:
for word, d in dict_split:
with open(word, 'w') as f:
for key, value in d.items():
f.write(f'{key}\n{value}\n')