How to create a dictionary using a list?


I have this list(newList) where I´m trying to create a dictionary with the product as a key and the price(identified with a $) as a value, while the output of the key is correct, the only key that has a value is the last one, and I dont know what I´m doing wrong, I would appreciate some help, thank you.

Here is a resumed version of the code I was trying

newList = ["banana", "apple", "$10", "$15"]
dict = {}
product = ""
price = ""
for i in newList:
  if "$" not in i:
    product = i
    price = i
  dict[product] = price

And this is the output:

{'banana': '', 'apple': '$15'}

Desired output:

{'banana': '$10', 'apple': '$15'}
Asked By: Zero



Split the list into two lists, then combine them into a dictionary.

products = [x for x in newList if not x.startswith("$")]
prices = [x for x in newList if x.startswith("$")]

product_prices = dict(zip(products, prices))
Answered By: Barmar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.