Andrew Bowman
Andrew Bowman

Reputation: 869

Modifying a python dictionary from user inputted dot notation

I'm trying to provide an API like interface in my Django python application that allows someone to input an id and then also include key/values with the request as form data.

For example the following field name and values for ticket 111:

ticket.subject = Hello World
ticket.group_id = 12345678
ticket.collaborators = [123, 4567, 890]
ticket.custom_fields: [{id: 32656147,value: "something"}]

On the backend, I have a corresponding Dict that should match this structure (and i'd do validation). Something like this:

ticket: {
    subject: "some subject I want to change",
    group_id: 99999,
    collaborator_ids: [ ],
    custom_fields: [
        {
            id: 32656147,
            value: null
        }
    ]
}

1) I'm not sure exactly the best way to parse the dot notation there, and 2) Assuming I am able to parse it, how would I be able to change the values of the Dict to match what was passed in. I'd imagine maybe something like a class with these inputs?

class SetDictValueFromUserInput(userDotNotation, userNewValue, originalDict)
    ...

SetDictValueFromUserInput("ticket.subject", "hello world", myDict)

Upvotes: 0

Views: 60

Answers (1)

Preston Hager
Preston Hager

Reputation: 1611

Fastest way is probably splitting the string and indexing based on seperation. For example:

obj = "ticket.subject".split(".")
actual_obj = eval(obj[0]) # this is risky, they is a way around this if you just use if statements and predifined variables. 
actual_obj[obj[1]] = value

To have further indexing where an object like ticket.subject.name might work try using a for loop as so.

for key in obj[1:-2]: # basically for all the values in between the object name and the defining key
  actual_obj = actual_obj[key] # make the new object based on the value in-between.
actual_obj[obj[-1]] = value

Upvotes: 1

Related Questions