0

I am learning programming in python 3 and I am having a issue with formating 2 for statements inside a list. Here is how I did it :

items = {
    "Iphone X": {"price": 1000, "stock":10},
    "Samsung S9": {"price": 800, "stock":10},
    "Huawei P20": {"price": 600, "stock":10},
    "HTC Vive": {"price": 400, "stock":10}
}
    test = ["{} - {}$".format(nume, pret) for nume in items.keys() for pret in items[nume]["price"]]
    print("\n".join(test))

I don't know why when I change the type of items[nume]["price"] into str it prints the key + the value , it prints it as many digits i have in my value.

If I don't change the type of items[nume]["price] it tells me TypeError: 'int' object is not iterable .

Sebastian
  • 84
  • 1
  • 12

1 Answers1

1

Just use .items() to access both the keys and values of your dictionary.

d = {'hammer':'5', 'scewdriver':'2'}

test = ["{} - {}$".format(k, v) for k,v in d.items()]
print("\n".join(test))
BernardL
  • 4,161
  • 3
  • 24
  • 44
  • Hey @BernardL, thank you for taking the time to answer my question, but as far as I know if I am doing the dictionary like that I won't be able to add stock as I have in mine right now. – Sebastian Oct 25 '18 at 19:26
  • @SebastianNeamtu select it by key, `["{} - {}$".format(k, v['price']) for k,v in d.items()]` – BernardL Oct 25 '18 at 20:43