1

I am trying to loop through a dict that I received via json and save the results to a database via sqlalchemy. I've kept the field names the same as the key names from the dict. It seems repetitive to list each field and dict over and over. But when I try to use something like c.keys() it does not work. If that were the case I could do: for key in c.keys(): customer.key = c[key]

But that does not work. My current code is:

for c in response['Customers']:
    customer = Customer()
    customer.ID = c['ID']
    customer.Name = c['Name']
    customer.Currency = c['Currency']
    customer.PaymentTerm = c['PaymentTerm']
    customer.Discount = c['Discount']
    customer.TaxRule = c['TaxRule']
    customer.Carrier = c['Carrier']
    session.add(customer)
session.commit()
4
  • what error happens with c.keys() ? Commented Jul 3, 2017 at 22:08
  • 1
    You should be able to go the other way: for key in c.keys(): setattr(customer, key, c[key]), something like that... or try dir(customer), that may give you more than you wanted though... Commented Jul 3, 2017 at 22:30
  • also, it looks like if you really want the keys, i can't guarantee this is stable, but customer._sa_instance_state.attrs.keys() looks like it will give them to you as well.... Commented Jul 3, 2017 at 22:31
  • Corley using for key in c.keys(): setattr(customer, key, c[key]) worked perfectly thanks! Commented Jul 3, 2017 at 23:37

2 Answers 2

1

You may use Python's setattr function, which as per the document:

setattr(object, name, value)

The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it.

For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

Hence you may write your code as:

for c in response['Customers']:
    customer = Customer()
    for key, value in c.items(): 
        setattr(customer, key, value)
        # ^ usage of `setattr(...)` here
    session.add(customer)

session.commit()

where I am assuming that you have all the properties defined in your class corresponding to the keys present in your dict object c.

Sign up to request clarification or add additional context in comments.

Comments

0

You could just unpack your dictionaries as arguments to __init__, given that you've not overridden the default constructor provided by Declarative that does exactly what the other answer does; it sets the attributes from the keyword arguments:

for c in response['Customers']:
    session.add(Customer(**c))

session.commit()

1 Comment

This is okay if you don't have to skip values or some additional input processing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.