Home > Mobile >  python writing to file exception occurs
python writing to file exception occurs

Time:10-30

"string indices must be integers" error occurs when using the code below.

global general_keys
general_keys = dict()
all_keys = {'activity': 'ins','install': 'all','aws.a': 'data', 'aws.b': 'data1', 'aws.c': 'data2'} 
general_key_array = ['install','db_manager', 'aws.']  

for key in general_key_array:
    for s in all_keys:
        if s.startswith(key):
            general_keys.update(dict(filter(lambda item: s in item[0], all_keys.items())))

file write section:

f.write("{0}{1}{2}".format("install=", general_keys['install']['install'], "\n"))
f.write("{0}{1}{2}".format("database_management_user=", general_keys['db_manager']['db_manager'], "\n"))
for key, value in general_keys['aws.'].items():
    f.write("{0}{1}{2}{3}".format(key, "=", value, "\n"))

expected output:

install=all
aws.a=data
aws.b=data1
aws.c=data2

enter image description here

CodePudding user response:

You're not creating nested dictionaries. The value of general_keys you're creating is:

{'install': 'all', 'aws.a': 'data', 'aws.b': 'data1', 'aws.c': 'data2'}

To create the nested dictionaries you want, use.

from collections import defaultdict

general_keys = defaultdict(dict)
all_keys = {'activity': 'ins','install': 'all','aws.a': 'data', 'aws.b': 'data1', 'aws.c': 'data2'} 
general_key_array = ['install','db_manager', 'aws.']  

for key1 in general_key_array:
    for key2, value in all_keys.items():
        if key2.startswith(key1):
            general_keys[key1][key2] = value

print(dict(general_keys))

Output:

{
    'install': {'install': 'all'}, 
    'aws.': {'aws.a': 'data', 'aws.b': 'data1', 'aws.c': 'data2'}
}
  • Related