Create a python function which sorts Python Dictionary by Keys.
no_of_entries = int(input('Enter no. of items you want in your dict: '))
lst = []
for i in range(no_of_entries):
key_in = input('Enter your key: ')
value_in = input('Enter your value: ')
tup1 = (key_in, value_in)
lst.append(tup1)
dictionary = dict(lst)
# print(dictionary)
def quiz_function(variable_as_dict):
list_of_key = list(variable_as_dict.keys())
list_of_value = list(variable_as_dict.values())
for i in range(len(list_of_key)):
for j in range(i+1, len(list_of_key)):
if list_of_key[i]>list_of_key[j]:
list_of_key[i], list_of_key[j] = list_of_key[j], list_of_key[i]
list_of_value[i], list_of_value[j] = list_of_value[j], list_of_value[i]
return dict(zip(list_of_key, list_of_value))
print(quiz_function(dictionary))
1 Like
dictionary = {}
no_of_entries = int(input('Enter no. of items you want in your dict: '))
for i in range(no_of_entries):
key_in = input('Enter your key: ')
value_in = input('Enter your value: ')
dictionary[key_in] = value_in
def quiz_function(variable_as_dict):
return dict(sorted(variable_as_dict.items()))
sorted_dictionary = quiz_function(dictionary)
print(sorted_dictionary)
1 Like
def sort_tuple_last(tuples):
return sorted(tuples, key=lambda x: x[-1]
sample_list = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
print(sort_tuple_last(sample_list))
def sort_dict_by_keys(d):
sorted_keys = sorted(d.keys())
sorted_dict = {}
for key in sorted_keys:
sorted_dict[key] = d[key]
return sorted_dict
my_dict = {‘c’: 3, ‘a’: 1, ‘b’: 2}
sorted_dict = sort_dict_by_keys(my_dict)
print(sorted_dict)
{‘a’: 1, ‘b’: 2, ‘c’: 3}