FAQ: Creating Dictionaries - What is a Dictionary?


#1

This community-built FAQ covers the “What is a Dictionary?” exercise from the lesson “Creating Dictionaries”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science

FAQs on the exercise What is a Dictionary?

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!


#2

More out of curiosity than a real problem… Why does the terminal print the dictionary differently than it is written in the compiler?

Compiler:
…sensors = {“living room”: 21, “kitchen”: 23, “bedroom”: 20, “pantry”: 22}…

printed:
{‘bedroom’: 20, ‘pantry’: 22, ‘living room’: 21, ‘kitchen’: 23}

At first I thought there had been some sorting applied before printing, but I can’t figure out any sorting logic behind the printed version.


#3

Dictionaries, like Ruby hashes and JS objects have no set insertion order. They are said to be unordered. The Collections library has an OrderedDict class, but that won’t be necessary in this course to use.

If you want to set the order the dictionary prints, such as sorted, then iterate over a sorted list of keys, and poll their values in the dictionary.

>>> for key in sorted(sensors.keys()):
    print ('{}: {}'.format(key, sensors[key]))

    
bedroom: 20
kitchen: 23
living room: 21
pantry: 22

This will also work, but is less explicit…

>>> for key in sorted(sensors):
    print ('{}: {}'.format(key, sensors[key]))

    
bedroom: 20
kitchen: 23
living room: 21
pantry: 22
>>>