alammd
alammd

Reputation: 339

Creating dictionary key and value from Variables giving syntax error

I am trying to create dictionary by providing key and value from variables, but I get syntax error:

disk_to_dm_dict = {}

for line in dm_name:
    match =  re.search(lun_reg,line)
    if match:
        lun=match.group(6)
        dm=match.group(8)
        print lun
        print dm
        #Create Dictionary with key= LUN and Value=dm
        disk_to_dm_dict['%s']%lun = dm

But I get error

 File "read_lun.py", line 42
    disk_to_dm_dict["%s"]%lun = dm
SyntaxError: can't assign to operator

Upvotes: 0

Views: 81

Answers (4)

mhawke
mhawke

Reputation: 87134

lun is already a string, which means that the key is in the required format. You can just do this:

disk_to_dm_dict[lun] = dm

To fix your code directly try:

disk_to_dm_dict['%s' % lun] = dm

That is move the % lun to be adjacent to the format string.

Upvotes: 0

Mani
Mani

Reputation: 949

Try to add key:value pair to dictionary using below snippet

disk_to_dm_dict[lun] = dm

Simple!

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124090

You need to apply the % operator to the string, not to the result of disk_to_dm_dict["%s"]. Python is complaining you are trying to assign to the outcome of something % something_else here.

Move the operator inside the [...] brackets to apply to the "%s" string:

disk_to_dm_dict["%s" % lun] = dm

Upvotes: 1

dmrz
dmrz

Reputation: 2443

You have an actual syntax error in the last line, here is the fixed variant:

disk_to_dm_dict['%s' % lun] = dm

Upvotes: 0

Related Questions