I'm building a function that takes a list which contains three different types of elements: integers, floats, and strings. The function converts the list to a dictionary with keys for each of these three different categories. Then each element in that original list is placed into the appropriate key-value pair (e.g. all string elements in the list get assigned to the "string" key). I'm able to get this working correctly, however I'm unable to sort the values inside the dictionary values (which are lists). Here's what I have:
def list_dict_sort(input_list):
mixed_list =['asdf', 33, 'qwerty', 123.45, 890, 3.0, 'hi', 0, 'yes', 98765., '', 25]
sorted_dict = {}
sorted_dict['integer'] = []
sorted_dict['float'] = []
sorted_dict['string'] = []
for x in mixed_list:
if "int" in str(type(x)):
sorted_dict['integer'].append(x)
elif "float" in str(type(x)):
sorted_dict['float'].append(x)
elif "str" in str(type(x)):
sorted_dict['string'].append(x)
sorted_dict.sort
return(sorted_dict)
list_dict_sort(mixed_list)
this returns:
{'float': [123.45, 3.0, 98765.0],
'integer': [33, 890, 0, 25],
'string': ['asdf', 'qwerty', 'hi', 'yes', '']}
so structurally the function gets me what I want, except that the value-lists are sorted. The exact output that I'd like is:
{'float': [3.0, 123.45, 98765.0],
'integer': [0, 25, 33, 890],
'string': ['asdf', 'hi', 'qwerty', 'yes', '']}
Ideally I want to avoid doing an import here (e.g. operator), I'm just looking for a simple/basic way of sorting the value-lists. I tried using sort
and sorted()
but couldn't figure out how to build them in to what I already have.
Is there a clean way of doing this or is there a more efficient way?