How to sort a dictionary: list by values ​​in a list?

I have a dictionary

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

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

The end result should be:

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

Or is a dictionary the wrong approach for such data?

+4
source share
5 answers

If you manipulate data, it often helps that each column is an observable variable (name, age), and each row is an observation (for example, a sampled person). Learn more about accurate data in this pdf link.

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

The list of dictionaries is better suited for such operations. Below I present a beginner-friendly snippet to organize your data. When you have a good data structure, sorting by any variable is trivial even for beginners. Not a single Python kung-fu liner :)

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

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 me sort it by person.name

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

Now return it to your format if you want

 >>> {'name': [p['name'] for p in persons], 'age': [p['age'] for p in persons]} {'age': [15, 30, 10], 'name': ['andy', 'janice', 'peter']} 
+9
source

zip used to create 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']} 
+2
source

Two-line version:

 >>> s = sorted(zip(mydict['name'], mydict['age'])) >>> dict([('name', [x[0] for x in s]), ('age', [x[1] for x in s])]) {'age': [15, 30, 10], 'name': ['andy', 'janice', 'peter']} 
+1
source

You can use defaultdict ( for faster work ) and zip - first zip person to the appropriate age then sort and then generate defaultdict and understanding of the dictionary.

 from collections import defaultdict dd= defaultdict(list) mydict = {'name':['peter', 'janice', 'andy'], 'age':[10, 30, 15]} d=zip(mydict['name'],mydict['age']) for i in sorted(d,key=lambda x: x[0]): dd['names'].append(i[0]) dd['age'].append(i[1]) print {k:v for k,v in dd.items()} 

Output -

 {'age': [15, 30, 10], 'names': ['andy', 'janice', 'peter']} 
0
source

Yes, maybe your approach with dictionnary is not the best. Here you just keep the list in litas. But you can also use a list to store these lists. That would be pretty much the same. First I suggest a voice recorder.

 myPeople = {} myPeople["peter"] = {"age":20, "country" : "USA"} myPeople["john"] = {"age":30, "country" : "newzealand"} myPeople["fred"] = {"age":32, "country" : "France"} # or if you have only one descript per name to store, # you may use only a dict # myPeopleName["peter"] = 20 # myPeopleName["john"] = 30 #then you iterate the dictionnary as before and the result will be print # out sorted by key for k in sorted(myPeople.keys()): print myPeople[k] 

Edit: my code was completely wrong. And the collection does not sort the value by key, but preserves the order of the key that you add in the dictionary.

-2
source

Source: https://habr.com/ru/post/1237628/


All Articles