设置表的输出顺序

时间:2015-05-19 19:53:30

标签: python python-2.7

我正在尝试生成报告并将下表打印到​​python中的文件:

from tabulate import tabulate
first_table_dict = {}
first_table_dict["Total agents"]        = len(agentUserIdDict)          
first_table_dict["Total users"]         = len(pure_user_dict)
first_table_dict["Users with agent"]    = len(pure_users_with_agents_dict)
first_table_dict["Users with invites"]  = len(user_id_invite_dict)
first_table_dict["RUURL accounts"]      = len(ruurl_set)
f.write(tabulate(first_table_dict.items(), headers = ["Category", "Total"]))

输出是:

Category              Total
------------------  -------
Users with invites    81533
Total users           90818
Users with agent      70060
Total agents          45571
RUURL accounts        81288

我知道词典没有订购。如何让列表按我想要的顺序?

3 个答案:

答案 0 :(得分:0)

你的问题是你期望的:

>>> {'a': 1, 'b': 2}.items()
[('a', 1), ('b', 2)]

事实上,有时你会得到

[('b', 2), ('a', 1)]

为什么不直接构建这个数据结构?

first_table = [
    ("Total agents"        , len(agentUserIdDict)),         
    ("Total users"         , len(pure_user_dict)), 
    ("Users with agent"    , len(pure_users_with_agents_dict)), 
    ("Users with invites"  , len(user_id_invite_dict)), 
    ("RUURL accounts"      , len(ruurl_set))
]
f.write(tabulate(first_table, headers = ["Category", "Total"]))

答案 1 :(得分:0)

from collections import OrderedDict
from tabulate import tabulate
b=OrderedDict()
b["Total agents"] = 45571
b["Total users"] = 90818
b["Users with agent"] = 70060
b["Users with invites"] = 81533
b["RUURL accounts"] = 81288

print tabulate(b.items(),headers = ["Category", "Total"])
Category              Total
------------------  -------
Total agents          45571
Total users           90818
Users with agent      70060
Users with invites    81533
RUURL accounts        81288

答案 2 :(得分:0)

哈希表没有排序(它违背了目的)。使用有序的数据结构或尝试以不同方式处理它。例如,如果您的数据来自数据库,则可以在数据库级别处理排序,并打印出输出中保存的数据。