Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Advanced Techniques and Strategies

Dattaram on April 1, 2020

For the last example, by_value is throwing error as undefined; NameError by_value is undefined

Liam Pulsifer RP Team on April 3, 2020

Hmm, @Dattaram did you make sure to define by_value as follows?

def by_value(item):
    return item[1]

Vedang Joshi on April 13, 2020

Do Python dictionaries always maintain the order in which the elements were added?

For Example: The method shown in the video:

>>> veggies
{'celery': 5, 'cabbage': 3, 'broccoli': 11}
>>> sorted_veggies = {k: veggies[k] for k in sorted(veggies)}
>>> sorted_veggies
{'celery': 5, 'cabbage': 3, 'broccoli': 11}
>>>
>>> for k in sorted(veggies):
...   print(k, ' -> ', veggies[k])
...
('broccoli', ' -> ', 11)
('cabbage', ' -> ', 3)
('celery', ' -> ', 5)
>>>

The order of items added is NOT maintained. However, if we use OrderedDict(), it is. @Liam Am I missing something?

>>> from collections import OrderedDict
>>>
>>> sorted_veggies = OrderedDict()
>>> for k in sorted(veggies):
...   sorted_veggies[k] = veggies[k]
...
>>> sorted_veggies
OrderedDict([('broccoli', 11), ('cabbage', 3), ('celery', 5)])
>>>

Dan Bader RP Team on April 14, 2020

Python dictionaries started retaining the insertion order with Python 3.6 (and above). More info here in this tutorial: realpython.com/python-dicts/#dictionary-keys-vs-list-indices

Vedang Joshi on April 14, 2020

Got it. Thanks

Liza Olariu on June 13, 2020

Hi Liam! Thanks for the great tutorials. For the last example, I think we might use the example below as well.

sorted_incomes = {key: value for key, value in sorted(incomes.items(), key=lambda item: item[1])}

Become a Member to join the conversation.