Python Sort Dictionaries
Python Sort Dictionaries
Output:
{'rajnish': 9, 'ravi': 10, 'sanjeev': 15, 'suraj': 32, 'yash': 2}
Python3
myKeys = list(myDict.keys())
myKeys.sort()
sorted_dict = {i: myDict[i] for i in myKeys}
print(sorted_dict)
Output
{'rajnish': 9, 'ravi': 10, 'sanjeev': 15, 'suraj': 32, 'yash': 2}
Output:
1 2 3 4 5 6
Python3
# Function calling
def dictionary():
# Declare hash function
key_value = {}
# Initializing value
key_value[2] = 56
key_value[1] = 2
key_value[5] = 12
key_value[4] = 24
key_value[6] = 18
key_value[3] = 323
print("Task 1:-\n")
print("key_value", key_value)
def main():
# function calling
dictionary()
Output
Task 1:-
Output:
[('rajnish', '9'), ('ravi', '10'), ('sanjeev', '15'), ('suraj',
'32'), ('yash', '2')]
Python3
Output
OrderedDict([('rajnish', '9'), ('ravi', '10'), ('sanjeev', '15'),
('suraj', '32'), ('yash', '2')])
Output:
(1, 2) (2, 56) (3, 323) (4, 24) (5, 12) (6, 18)
Python3
# function calling
def dictionairy():
# Initialize value
key_value[2] = 56
key_value[1] = 2
key_value[5] = 12
key_value[4] = 24
key_value[6] = 18
key_value[3] = 323
print("key_value",key_value)
def main():
# function calling
dictionairy()
Output
key_value {2: 56, 1: 2, 5: 12, 4: 24, 6: 18, 3: 323}
Task 2:-
Keys and Values sorted in alphabetical order by the key
(1, 2) (2, 56) (3, 323) (4, 24) (5, 12) (6, 18)
Output:
[(1, 2), (5, 12), (6, 18), (4, 24), (2, 56), (3, 323)]