Home > front end >  Create a csv file with value from a dictionary in python
Create a csv file with value from a dictionary in python

Time:03-01

Create a new file output.csv in the outcome folder. The first row in the file contains three column names ID, pan and pen. The following 1000 rows contain the following three column values: the first column has row IDs ranging from 1 to 1000 and the second column has strings of 5-10 random digits. Rows are separated by a new line and columns by a comma. The third column has code strings, each character of which is the corresponding value for the key in the dictionary d. For example, if the random string of digits is '3164482864', its corresponding code string is '#!^$$@^$', as '3' is mapped to '#', '1' is to '!', so on and so forth. Rows are separated by a new line and columns by a comma.

The dictionary: d = { "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", "8": "*", "9": "(", "0": ")", }

This is what it should look like: Id,pan,pen 1,3164482864,#!^$$@^$ 2,2233297733,@@##@(&&## 3,7713718,&&!#&!* 4,373982531,#&#(*@%#!

This is what i have-

with open("outcome/hw2_output2.csv", mode="w") as fw:
    fw.write("rid,num,code\n")
         
    for i in range(1000):
        Id = i
        pan = generate_random_string(string.digits, 5, 10)
        **pen = "".join([random.choice(string.digits) for i in **
        
               
        fw.write(f"{rid},{num},{code}\n")

Please help!

CodePudding user response:

import random
import csv

d = { "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", "8": "*", "9": "(", "0": ")", }


def get_pen(pan):
    pen = ""
    for i in pan:
        pen  = d[i]
    return pen


with open("hw2_output2.csv", 'w', newline='') as file:
    writer = csv.writer(file)
    
    # write first row
    writer.writerow(["id","pan","pen"])

    for id in range(1000):

        #get random str with length 5-10
        pan = str(random.randrange(10000, 10000000000))
        pen = get_pen(pan)
        
        # write row
        writer.writerow([id,pan,pen,])

CodePudding user response:

You are generating a mapping of characters. Here are the steps to create what you need.

import random
import string
CHAR_MAP = {"1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", "8": "*", "9": "(", "0": ")"}
with open(file_path, 'w') as fw:
  for i in range(1000):
    num = "".join([random.choice(string.digits) for _ in range(random.randint(5, 10))])
    code = "".join([d[x] for x in num])
    fw.write(f'{i},{num},{code}\n')

Create the a random series of character from the set. In this case the set are digits.

  num = "".join([random.choice(string.digits) for _ in range(random.randint(5, 10))])

Create code by mapping the dictionary CHAR_MAP onto the generated random sequence.

  code = "".join([d[x] for x in num])

And finally writing CSV row:

  fw.write(f'{i},{num},{code}\n')
  • Related