Home > database >  Python : Open file and take value from it and pass in to dictionary
Python : Open file and take value from it and pass in to dictionary

Time:07-15

data={'name':"1.1.1.1",'subnet'="1.1.1.1/32",'id'=3,'env'="PROD"}

Now only changing key is name and subnet, id and env remain same. while passing name and subnet value must be inside "".

input file like be 1.1.1.1 1.1.1.1/32

with open("file1.txt") as f:
     for i in f:
         value_string=str(i)
         data={'name':' value_string ','subnet'="1.1.1.1/32",'id'=3,'env'="PROD"}
         pprint(data)

But its doesnt have value in "" and how i can pass value in subnet.

CodePudding user response:

I'd imagine you're looking for something like

with open("file1.txt") as f:
    for line in f:
        ip, subnet = line.strip().split(None, 1)
        data = {"name": ip, "subnet": subnet, "id": 3, "env": "PROD"}
        pprint(data)

CodePudding user response:

Please see my solution below:

data = dict()

with open('file.txt', 'r') as f:
    for line in f:
        data['name'], data['subnet'], data['id'], data['env'] =  line.split(' ')[0], line.split(' ')[1], '3', 'PROD'
  • Related