Computer Science
Can you change the order of dictionary's contents, i.e., can you sort the contents of a dictionary ?
Python Dictionaries
8 Likes
Answer
No, the contents of a dictionary cannot be sorted in place like that of a list. However, we can indirectly sort the keys and values of a dictionary by using sorted() function:
- sorted(dictionary.keys())
- sorted(dictionary.values())
- sorted(dictionary)
- sorted(dictionary.items())
For example:
>>> d = {"def" : 2 ,"abc" : 1, "mno" : 3}
>>> sorted(d.keys())
>>> sorted(d.values())
>>> sorted(d)
>>> sorted(d.items())
Output
['abc', 'def', 'mno']
[1, 2, 3]
['abc', 'def', 'mno']
[('abc', 1), ('def', 2), ('mno', 3)]
Answered By
2 Likes
Related Questions
Though tuples are immutable type, yet they cannot always be used as keys in a dictionary. What is the condition to use tuples as a key in a dictionary ?
What all types of values can you store in :
- dictionary-values ?
- dictionary-keys ?
In no more than one sentence, explain the following Python error and how it could arise:
TypeError: unhashable type: 'list'
Can you check for a value inside a dictionary using in operator? How will you check for a value inside a dictionary using in operator ?