Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added.
What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?
For example, you had this:
d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
I want to print the associated values in the following sequence sorted by key:
this is a
this is b
this is c
items() method is used to return the list with all dictionary keys with values. It returns a view object that displays a list of a given dictionary's (key, value) tuple pair. sorted() is used to sort the keys of the dictionary.
Introduction. We can sort lists, tuples, strings, and other iterable objects in python since they are all ordered objects. Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python's built-in sorted() function.
Do you mean that you need the values sorted by the value of the key? In that case, this should do it:
for key in sorted(d):
print d[key]
EDIT: changed to use sorted(d) instead of sorted(d.keys()), thanks Eli!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With