How to create a dictionary from a list or iterate through a list in Python [closed]

I have a list in this format:

[{'Item_ID': 01, 'price': 5, 'quantity': 5}, ... ]

I’m trying to get the ‘price’ from this list for each item ID to store into a new list, but I’m not sure how to get that information. I looked at tutorials for changing a list to a dictionary but they seem to be mostly geared toward 1 key/value pair while this list has 3 key value pairs per item. I’m not really sure how to pull out the information I need, which is essentially the value of ‘price’ in all of the items in the list.

  • 1

    Use a list comprehension to iterate over each element in the list and grab the price. [d.get('price', 0) for d in x] where your list would assigned to the variable x

    – 




  • 1

    You forgot to post your attempt to solve even part of this problem.

    – 

  • 1

    Also what’s the expected output, just a list of prices? I’d imagine you would want a list of dicts of Item_ID with its price?

    – 




Leave a Comment