Python - Dynamically Populate Variable

时间:2015-07-28 16:45:14

标签: python

Suppose I have the following data in read.txt:

_app1_ip_
_app2_ip_
_app1_ip_
_app3_ip_
_app2_ip_

And I want to replace each with a certain corresponding value (in this case, the values in 'list') and output that to another file (out.txt):

list = ['app1', 'app2', 'app3']

for l in list:
   field = '_%s_ip_' %l

   patterns = {
      field : l,
   }

   with open("read.txt", "r") as my_input:
      content = my_input.read()
   with open("out.txt", "w+") as my_output:
      for i,j in patterns.iteritems():
         content = content.replace(i,j)
         my_output.write(content)

What I want is the following in data.txt:

app1
app2
app1
app3
app2

What I actually get is:

_app1_ip_
_app2_ip_
_app1_ip_
app3
_app2_ip_

This seems so simple.. would be an easy one-liner in bash/sed. Can anyone please help/explain?

1 个答案:

答案 0 :(得分:1)

After

list = ['app1', 'app2', 'app3']
for l in list:
    field = '_%s_ip_' %l
    patterns = {
        field : l,
    }

patterns only contains the last value, i.e.

patterns = {'_app3_ip_': 'app3'}

because you overwrite patterns in every loop iteration. Instead, you want to populate that dictionary. You can either do that with a for loop like you used:

list = ['app1', 'app2', 'app3']
patterns = {}
for l in list:
    field = '_%s_ip_' % l
    patterns[field] = l

or by using a dictionary comprehension:

patterns = {'_%s_ip_' % l: l for l in ['app1', 'app2', 'app3']}