Reputation: 849
Im trying to parse results from Prestashop API. I prepared that code.
prestashop = PrestaShopWebServiceDict( URL, API_KEY )
def get_order(order_id):
orders = order_id.split(",")
for order in orders:
order = prestashop.get('orders', order)['order']
for product in products['order_row']:
print product['product_reference']
It works properly when order are associated with few products, and result look like:
[
{'product_id': '6', 'price': '39.000000', 'product_reference': '000001'},
{'product_id': '7', 'price': '38.000000', 'product_reference': '000002'},
{'product_id': '8', 'price': '37.000000', 'product_reference': '000003'},
]
result:
000001 000002 000003
In a situation where the order contains only one product, and the result is like:
{'product_id': '6', 'price': '39.000000', 'product_reference': '000001'}
I cant loop it by:
for product in products['order_row']:
print product['product_reference']
Because:
Traceback (most recent call last):
File "prestapyt_dict.py", line 30, in <module>
print product['product_reference']
TypeError: string indices must be integers, not str
I have no idea how to solve it. The only thing comes to my head is check dictionary depth, but I do not know if it is a good solution.
Upvotes: 4
Views: 80
Reputation: 846
In the first example of the three objects, you're given a list of the three dictionaries (note: in the list!) so you're able to loop through each dictionary like normal. In the second example, however, this...
for product in products['order_row']:
turns this...
{'product_id': '6', 'price': '39.000000', 'product_reference': '000001'}
... into something different. Because it's not a list and it's one dictionary, you're going into the dictionary rather than into the list. You're now trying to get the index of 'product_id', which you need [#s] to do since it's a string (e.g. to get 'r' you would need 'product_id'[1]) and you're given an (Type) error because you provide a string instead.
The pythonic way to do this would be to expect the error, catch it and do something else:
try:
for product in products['order_row']:
print product['product_reference']
except TypeError:
#something else
Alternatively, you can add the dictionary to an empty list as suggested in one of the comments and your for loop will loop over that list for the entirety of that one item.
Upvotes: 3