jeffery_the_wind jeffery_the_wind - 1 month ago 7
Python Question

getting key-value pairs of custom object in python

I am working with the python boto package called mws for interfacing with Amazon MWS. But I think this is also a general python question, still not sure. I am using the

list_oder_items
method to get the product items for an order.

items = conn.list_order_items(AmazonOrderId = order_id)
result = items.ListOrderItemsResult


Then I will want to save each item.

for item in result.OrderItems.OrderItem:
save_item_to_db(item)


Here the
item
variable is a type
<class 'boto.mws.response.OrderItem'>
, which if you print it out shows this:


OrderItem{}(Title: u'title',
GiftWrapPrice: USD 0.00, ConditionNote: u'Brand New& Authentic
product....', CODFee: None, ASIN: u'XXXX', OrderItemId:
u'XXXX', CODFeeDiscount: None, QuantityShipped: u'1',
GiftWrapTax: USD 0.00, ShippingPrice: USD 3.99, QuantityOrdered: u'1',
ItemTax: USD 0.00, PromotionIds: [], SellerSKU:
u'XXXX', ShippingDiscount: USD 0.00, ShippingTax: USD
0.00, ConditionId: u'New', PromotionDiscount: USD 0.00, ItemPrice: USD 12.81, ConditionSubtypeId: u'New')


why can't I iterate over the key-value pairs like
for key in item: print key
? Just a silly though I also tried this:
for key in dict(item): print key
. That didn't print anything either.

I would just like to have a more systematic approach for dealing with the
item
object than visual inspection. Is it possible to turn it into a normal python dict?

Answer

Basically you are getting an object and you want to iterate over all the fields of that object as key:value pair.

You can try object._dict_ to get dictionary representation of the object.

code example:

for key in item.__dict__:
    print key