Home > database >  How to create a dictionary using a list?
How to create a dictionary using a list?

Time:11-24

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
  else:
    price = i
  dict[product] = price
print(dict)

And this is the output:

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

Desired output:

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

CodePudding user response:

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))
  • Related