Search code examples
pythondictionarysyntaxfunction-call

Dictionary keys with a dot does not work with update()?


I would like to use a dictionary parDict with keys that contain a dot and find that the update function does not interpret keys with dots, although the dictionary works fine. The dot-notation is due to object-orientation of the set of parameters.

The following example illustrate the "inconsistency".

parDict = {}
parDict['a'] = 1
parDict['b'] = 2
parDict['group1.b'] = 3 

Several updates of parDict can be done in one command which is important for me

parDict.update(a=4, b=4)

But the the following update is NOT recognized

parDict.update(group1.b=4)

and I get: "SyntaxError: expression cannot contain assignment, ..."

However,

parDict['group1.b'] = 4

works fine.

Is here a way to work around this "inconsistency" to use update() even for keys with a dot in the name?

Would be interesting to perhaps understand the wider context why update() does not work here.


Solution

  • I am glad for the input I have got on my questions around parDict, although my original neglect of the difference between "keys" and "identifiers" is very basic. The purpose I have in mind is to simplify command-line interaction with an object-oriented parameter structure. It is a problem of some generality and perhaps here are better solutions than what I suggest below?

    Using update() with tuples is attractive, more readable and avoid using a few signs as pointed out at the link @wjandrea posted. But to use it this way we need to introduce another dictionary, i.e. we have parDict with short unique parameter names and use identifiers and corresponding values, and then introduce parLocation that is a dictionary that relates the short names parameter names to the location object-oriented string.

    The solution

    parDict = {}
    parDict['a'] = 1
    parDict['b'] = 2
    parDict['group1_b'] = 3
    

    and

    parLocation = {}
    parLocation['a'] = 'a'
    parLocation['b'] = 'b'
    parLocation['group1_b'] = 'group1.b'
    

    For command line-interaction I can now write

    parDict.update(b=4, group1_b=4)
    

    And for the internal processing where parameter values are brought to the object-oriented system I write something like

    for key in parDict.keys(): set(parLocation[key], parDict[key])
    

    where set() is some function that take as arguments parameter "location" and "value".

    Since the problem has some generality I though here might be some other better or more direct approach?