如何按列表中的值排序一个键:列表字典? [英] How do I sort a key:list dictionary by values in list?

查看:161
本文介绍了如何按列表中的值排序一个键:列表字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本字典

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

on key ==namelist?

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

最终结果应该是:

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

或者是为这样的数据输入错误的方法?

Or is dictionary the wrong approach for such data?

推荐答案

如果您操纵数据,通常它有助于每列是观察变量(名称,年龄),每行都是观察值(例如抽样人员)。本 PDF链接中有关整理数据的更多信息

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


错误的程序员担心代码。好的程序员担心
数据结构和他们的关系 - Linus Torvalds

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

字典列表更适合这样的操作。下面我提供一个初学者友好的片段来整理你的数据。一旦你有一个好的数据结构,任何变量排序是微不足道的,即使是初学者。没有一行Python功夫:)

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'}]

现在,这个数据结构的工作更容易,类似于数据框在数据分析环境中。让我们按 person.name 分类

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'])

如果你想要

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

这篇关于如何按列表中的值排序一个键:列表字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆