View Single Post
  #1  
Old 05-05-2019, 02:38 AM
slouw slouw is offline
Registered User
 
Join Date: Nov 2005
Posts: 166
Reference a new dictionary key with a variable

I want to read files with parameters and assignments in order to configure a new device.
It seemed correct to read variables and their assignments into a dictionary from a text file.
But I have hit a snag in that I cannot work out how to read variables directly into a dictionary.
I have stripped down my script to the following to try and illustrate this.



Quote:
# $language = "python"
# $interface = "1.0"
#
import time
import datetime
import sys

#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# This is how I want me dictionary to look after
# assignment from reading a text file
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Dict_Param = {
"<IP_ADDRESS>": "10.10.10.10",
"<PREFIXLENGTH>": "24",
"<HOSTNAME>": "blahblah"
}


Dict_Param = {}

#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Variables and their assignments are read from
# a text file into 2 lists as shown
# I have this working just stripped out for simplicity
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
KeyStr = ["<IP_ADDRESS>","<PREFIXLENGTH>","<HOSTNAME>"]
AssignStr = ["10.10.10.10", "24", "blahblah"]

#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# This does not work
# But I hope it illustrates what I am trying
# and failing to do
# That is add the pairs defined in the 2 lists above
# as key entries in my dictionary
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Dict_Param['KeyStr[0]'] = AssignStr[0]
Dict_Param['KeyStr[1]'] = AssignStr[1]
Dict_Param['KeyStr[2]'] = AssignStr[2]

print Dict_Param
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Reply With Quote