Python : SyntaxError: keyword can't be an expression

时间:2017-05-16 09:14:45

标签: python ios dictionary

Not sure where the issue is, i tried using multiple variables names to this dict with the same error:

>>> hostname=dict('172.16.1.75'='N-Switch', '172.16.1.76' = 'W-Switch', '172.16.1.77' = 'E-Switch')
SyntaxError: keyword can't be an expression

I am trying to create a dictionary for a script to change hostnames on assets based by calling their IP address as the key. any idea where the issue is?

3 个答案:

答案 0 :(得分:3)

The usual format for initiallizing a dict is like this

hostname=dict([('172.16.1.75','N-Switch'), ('172.16.1.76','W-Switch'), ('172.16.1.77', 'E-Switch')])

or more simply as given by Carles Mitjans in his answer (which appears to have been delete so adding the gist of it here for the benefit of < 10k users)

 hostname={'172.16.1.75':'N-Switch', '172.16.1.76' : 'W-Switch', '172.16.1.77' : 'E-Switch'}

This is in fact the more usual way of using dictionaries in python. The dict built in is used only when you are working with dynamic lists.

Also possible is a dictionary comprehension.

答案 1 :(得分:2)

I am not sure you are using valid syntax, try:

hostname={'172.16.1.75':'N-Switch', '172.16.1.76' : 'W-Switch', '172.16.1.77' : 'E-Switch'}

答案 2 :(得分:0)

As the error says, parameters can't be strings. The solution would be to create a dictionary using {} constructor:

hostname={'172.16.1.75':'N-Switch', '172.16.1.76' : 'W-Switch', '172.16.1.77' : 'E-Switch'}

If you wish to use the dict constructor you need to provide valid parameters as keys (not strings).