[Solved] How to iterate over a dictionary and a list simultaneously? [closed]


You can use:

  • maketrans–which allows creation of a translation table
  • translate–applies translation table from maketrans to a string

Code

def encrypt(infile, outfile, translation):
    '''
        Encrypts by applying translation map to characters in file infile.
    '''
    # Create translation table
    table="".maketrans(translation)
    
    # Apply table to all characters in input file
    # and write to new output file
    with open(infile, "r") as fin, open(outfile, "w") as fout:
        for line in fin:
            fout.write(line.translate(table))
 

Test

# Dictionary containing map of letters to their new values
d = {"H":"a", "e":"d", "l": "k", "o":"n"}

# Encryp filel 'input.txt'
encrypt('input.txt', "output.txt", d)

# Show Result
print(open("output.txt").read())     

Input file ‘input.txt:

Hello
World

Output file ‘output.txt’ (letters specified in dictionary d are replaced)

adkkn
Wnrkd

solved How to iterate over a dictionary and a list simultaneously? [closed]