Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort a key:list dictionary by values in list?

I have a dictionary

mydict = {'name':['peter', 'janice', 'andy'], 'age':[10, 30, 15]}

How do I sort this dictionary based on key=="name" list?

End result should be:

mydict = {'name':['andy', 'janice', 'peter'], 'age':[15, 30, 10]}

Or is dictionary the wrong approach for such data?

like image 779
user2979010 Avatar asked Dec 25 '22 11:12

user2979010


2 Answers

If you manipulate data, often it helps that each column be an observed variable (name, age), and each row be an observation (e.g. a sampled person). More on tidy data in this PDF link

Bad programmers worry about the code. Good programmers worry about data structures and their relationships - Linus Torvalds

A list of dictionaries lends itself better to operations like this. Below I present a beginner-friendly snippet to tidy your data. Once you have a good data structure, sorting by any variable is trivial even for a beginner. No one-liner Python kung-fu :)

>>> mydict = {'name':['peter', 'janice', 'andy'], 'age':[10, 30, 15]}

Let's work on a better data structure first

>>> persons = []
>>> for i, name in enumerate(mydict['name']):
...     persons.append({'name': name, 'age': mydict['age'][i]})
... 
>>> persons
[{'age': 10, 'name': 'peter'}, {'age': 30, 'name': 'janice'}, {'age': 15, 'name': 'andy'}]

Now it's easier to work on this data structure which is similar to "data frames" in data analysis environments. Let's sort it by person.name

>>> persons = sorted(persons, key=lambda person: person['name'])

Now bring it back to your format if you want to

>>> {'name': [p['name'] for p in persons], 'age': [p['age'] for p in persons]}
{'age': [15, 30, 10], 'name': ['andy', 'janice', 'peter']}
like image 108
bakkal Avatar answered Jan 12 '23 23:01

bakkal


zip is used to make tuples (name, age)

dict = {'name':[], 'age':[]}
for name, age in sorted(zip(mydict['name'], mydict['age'])):
    dict['name'].append(name)
    dict['age'].append(age)

output:

{'age': [15, 30, 10], 'name': ['andy', 'janice', 'peter']}
like image 24
Kenly Avatar answered Jan 12 '23 21:01

Kenly