Issue
Edit: Apologies - after reading the comments I realized this is a dictionary of dictionaries(?)
The answer that solved this is to change it to ...price_list["market"].values() in the for loop. Thanks a lot.
Original:
I'm getting a value back from an API in this kind of format:
{'market': {'14912878': {'cost': 45695, 'quantity': 2000, 'total_cost': 91390000},...}
I'm trying to iterate over this to pull the 'cost' for each item ID (the '14912878' here, but there are many others).
Here's what I've tried, but it's saying I can't run get on a str, because it's pulling the item ID. I'm not sure how to iterate over the item IDs to pull out the 'cost' (not the total_cost).
price_list = [price.get('cost',0) for price in item_list["market"]]
I also tried to put it in a for loop:
for item in price_list["market"]:
price_list = [price.get('cost',0) for price in item_list["market"][item]]
If anyone could help I'd appreciate it.
Solution
data = {
'market': {
'14912878': {'cost': 45695, 'quantity': 2000, 'total_cost': 91390000},
# ... other items
}
}
for item_id, item_data in data['market'].items():
cost = item_data['cost']
print(f"Item ID: {item_id}, Cost: {cost}")
# or for one-liner
costs = [item['cost'] for item in data['market'].values()]
Answered By - Milos Stojanovic
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.