Python | Sort Python Dictionaries by Key or Value
Prerequisite:
Problem Statement – Here are the major tasks that are needed to be performed.
- Create a dictionary and display its keys alphabetically.
- Display both the keys and values sorted in alphabetical order by the key.
- Same as part (ii), but sorted in alphabetical order by the value.
Approach –
Load the Dictionary and perform the following operations:
- First, sort the keys alphabetically using key_value.iterkeys() function.
- Second, sort the keys alphabetically using sorted (key_value) function & print the value corresponding to it.
- Third, sort the values alphabetically using key_value.iteritems(), key = lambda (k, v) : (v, k))
Let’s try performing the above-mentioned tasks:
- Displaying the Keys Alphabetically:
Examples:
Input: key_value[2] = '64' key_value[1] = '69' key_value[4] = '23' key_value[5] = '65' key_value[6] = '34' key_value[3] = '76' Output: 1 2 3 4 5 6
Program:
Output:Task 1:- Keys are 1 2 3 4 5 6
- Sorting the Keys and Values in Alphabetical Order using the Key.
Examples:
Input: key_value[2] = '64' key_value[1] = '69' key_value[4] = '23' key_value[5] = '65' key_value[6] = '34' key_value[3] = '76' Output: (1, 69) (2, 64) (3, 76) (4, 23) (5, 65) (6, 34)
Program:
Output:Task 2:- Keys and Values sorted in alphabetical order by the key (1, 2) (2, 56) (3, 323) (4, 24) (5, 12) (6, 18)
- Sorting the Keys and Values in alphabetical using the value
Examples:
Input: key_value[2] = '64' key_value[1] = '69' key_value[4] = '23' key_value[5] = '65' key_value[6] = '34' key_value[3] = '76' Output: (4, 23), (6, 34), (2, 64), (5, 65), (1, 69), (3, 76)
Program:
Output:Task 3:- Keys and Values sorted in alphabetical order by the value [(1, 2), (5, 12), (6, 18), (4, 24), (2, 56), (3, 323)]
Sort the dictionary by key
Note:it will sort in lexicogrphical order
Taking key’s type as string
Program:
Here, Output is Soretd Dictionary using key in Lexicolographical order
Lexicographical order:https://en.wikipedia.org/wiki/Lexicographical_order
Learning Outcome:
- How to handle a dictionary.
- Dictionary has O(1) search time complexity whereas List has O(n) time complexity. So it is recommended to use the dictionary where ever possible.
- The best application of dictionary can be seen in Twitter Sentiment Analysis where analysis Twitter sentiments are analysed, using Lexicon approach.
No comments:
Post a Comment
Your feedback is highly appreciated and will help us to improve our content.