简体   繁体   English

根据值对Python字典排序

[英]Sort Python Dictionary based on Values

I have the following program which reads from a tsv file and imports to a dictionary. 我有以下程序,该程序从tsv文件读取并导入字典。 I need to sort the dictionary based on jobID and its giving me this error: 我需要根据jobID对字典进行排序,并给我这个错误:

AttributeError: 'dict' object has no attribute 'jobid' AttributeError:'dict'对象没有属性'jobid'

  apps = {}
  for row in csvreader:
    apps[counter]= {'userid': row[0], 'time': row[1], 'jobid': row[2]}
    counter = counter + 1

  sorted_keys = sorted(apps.keys(), key=lambda x:apps.jobid)

Any an all help is appreciated. 任何所有的帮助表示赞赏。

sample output for the first three rows in the dict: 字典前三行的样本输出:

{'jobid': 'JobID', 'userid': 'UserID', 'time': 'ApplicationDate'}

{'jobid': '169528', 'userid': '47', 'time': '2012-04-04 15:56:23.537'}

{'jobid': '284009', 'userid': '47', 'time': '2012-04-06 01:03:00.003'}

Thank You! 谢谢!

看来您想使用apps[x]["jobid"]而不是apps.jobid

You should use a list for apps. 您应该使用应用列表。 Then you can sort on jobid by using the dictionary lookup syntax x['jobid']. 然后,您可以使用字典查找语法x ['jobid']对Jobid进行排序。 Here it is working with sample data: 它在这里处理示例数据:

csvreader = (
    ('user1', '2pm', 2),
    ('user2', '2pm', 3),
    ('user3', '2pm', 1)
)

apps = []
for row in csvreader:
    apps.append({'userid': row[0], 'time': row[1], 'jobid': row[2]})

sorted_data = sorted(apps, key=lambda x:x['jobid'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM