Search code examples
pythonstring-concatenation

Python: create a new variable with the values of 2 separate lists


I am running probes on a number of campus devices daily and log the Probe for each day to a file that takes the name: HOST-YYMMDD.txt (e.g. "Host1-Loc1-171219.txt")

I am trying to automate the generation of variables that would allow xlsxwriter to 'read' the correct files for the loops that I need to run afterwards.

H1L1 = "Host1-Loc1"
H1L2 = "Host2-Loc2"

Dates = [171219,171220,171221]
Hosts = [H1L1,H1L2]

I am trying to create variables using the name pattern "Probe[Date]" (e.g. "Probe171219", "Probe171220" etc.) that are equal to (respectively) the log files "Host1-Loc1-171219.txt" and "Host1-Loc1-171220.txt"

I have been able to print the value that I need to get for the Probe variables, but I've not managed to assign it to an actual variable in an automatic way.

for item in Dates:
   print('FileLocation',Hosts[0],'-',item,'.txt',sep='')

This prints:

FileLocation/Host1-Loc1-191219.txt
FileLocation/Host1-Loc1-191220.txt

The question is how do I assign this to variables that would be called "Probe171219" and "Probe171220", thus giving the result:

Probe171219 = FileLocation/Host1-Loc1-191219.txt
Probe171220 = FileLocation/Host1-Loc1-191220.txt

This far I've been populating my variables manually, but with over 50 new logs per day, it is not very salable.


Solution

  • As pault mentioned you can use a dictionary:

    Sample:

    Dates = [171219,171220,171221]
    Hosts = ["H1L1","H1L2"]
    d = {}
    for i in zip(Dates,Hosts):
        d["Probe{0}".format(i[0])] = "FileLocation/{0}.txt".format(i[1])
    
    print d
    

    Result:

    {'Probe171219': 'FileLocation/H1L1.txt', 'Probe171220': 'FileLocation/H1L2.txt'}