Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update an object's members using a dict?

Tags:

python

django

I'm writing a Django app that performs various functions, including inserting, or updating new records into the database via the URL.

So some internal application sends off a request to /import/?a=1&b=2&c=3, for example. In the view, I want to create a new object, foo = Foo() and have the members of foo set to the data in the request.GET dictionary.

Here is what I'm doing now:

  1. Request sent to /import/?a=1&b=2&c=3
  2. View creates new object: foo = Foo()
  3. Object is updated with data.

Here is what I got thus far:

foo.a = request['a']
foo.b = request['b']
foo.c = request['c']

Obviously this is tedious and error prone. The data in the URL has the exact same name as the object's members so it is a simple 1-to-1 mapping.

Ideally, I would like to do able to do something like this:

foo = Foo()
foo.update(request.GET)

or something to that effect.

Thanks!

like image 836
Nick Presta Avatar asked Jun 02 '09 15:06

Nick Presta


People also ask

Which method is used to update value for a particular key in a dictionary?

Python Dictionary update() Method Python update() method updates the dictionary with the key and value pairs. It inserts key/value if it is not present. It updates key/value if it is already present in the dictionary. It also allows an iterable of key/value pairs to update the dictionary.

Can we update key in dictionary?

Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value.

Can you modify dict in Python?

Modifying a value in a dictionary is pretty similar to modifying an element in a list. You give the name of the dictionary and then the key in square brackets, and set that equal to the new value.


2 Answers

You can use the setattr function to dynamically set attributes:

for key,value in request.GET.items():
    setattr(foo, key, value)
like image 170
Ants Aasma Avatar answered Nov 15 '22 15:11

Ants Aasma


If request.GET is a dictionary and class Foo does not use __slots__, then this should also work:

# foo is a Foo instance
foo.__dict__.update(request.GET)
like image 28
tzot Avatar answered Nov 15 '22 17:11

tzot