Keeping Track of the Produce - I got the code right, but what if I want to order the dictionary items of {prices} and {stock}?


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/python-beginner-en-IZ9Ra/1/3?curriculum_id=4f89dab3d788890003000096

<In what way does your code behave incorrectly? Include ALL error messages.>
Keeping Track of the Produce - I got the code right, but what if I want to order the dictionary items of {prices} and {stock}?

Remembering: my code is ok! syntax and everything. The program run it, but then I turn back to the problem and wanted to add the .sort() function:

as prices.sort()
stock.sort()

Then I had the following issue:
File “python”, line 15
prices.sort()

how do I do that? How do I code the dictionary items to be printed out in an alphabetical order?

By the way, is here my code:

prices = {
“banana”: 4,
“apple”: 2,
“orange”: 1.5,
“pear”: 3
}

stock = {
“banana”: 6,
“apple”: 0,
“orange”: 32,
“pear”: 15
}

prices.sort()
stock.sort()

for key in prices:
print(key)
print(“price: %s” % prices[key])
print(“stock: %s” % stock[key])

…--------------…-------------------…

should I write something as: def prices.sort()
print(prices.sort)

<What do you expect to happen instead?>
Waiting for a possible answer

```python

Replace this line with your code.

<do not remove the three backticks above>

#2

you would need to sort the keys, what you could do is create an empty list, append all the keys to the list, then sort the list, now we have the keys sorted and stored in a list, so we can loop over the list to get the keys in alphabetic order


#3

Dictionaries are unorderd and not sortable, at least not with list.sort(). The order in which we read them is not predictable.


#4

I still don’t get it…would you mind in writing that part, about the empty list and so.


#5

no? That is your job. I am here to help, not code for you, you need to learn this :wink: You just need to define a list and get all the dictionary keys in that list, you should have the knowledge to achieve this


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.