首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python,对字典进行排序

Python,对字典进行排序
EN

Stack Overflow用户
提问于 2012-09-04 22:58:23
回答 2查看 286关注 0票数 2

我正在用python写一个字典。我正在尝试按字母顺序对其进行排序,并将其拆分以使其看起来更好一些。这是我到目前为止在字典中拥有的代码。

代码语言:javascript
复制
authorentry = {'author':  name, 'date': datef , 'path': path_change , 'msg' : xmlMsgf }           
if not name in author:
    author[ name ] = []

author[ name ].append( authorentry )       

if not authorentry in author.items():
    author['author'] = [authorentry]

print sorted (author.keys()), sorted (author.values())

现在我要做的就是按照作者和日期的排序顺序打印出字典。并且拆分和修改它,这样它就不会有那些逗号和‘u’,如果可能的话。你有什么想法来实现它吗?

这是我按原样打印出来的样子。

我想要的是作者在列表中排在第一位,而不是日期。如果可能的话,我希望它按字母顺序排列,并去掉入口中的逗号,以便更清晰地打印出来。有可能吗?

代码语言:javascript
复制
[[{'date': ['06-08-2012 09:01:52 PM'], 'path': [u'/branches/Patch_4_2_0_Branch'], 'msg': ['none', u'PATCH_BRANCH:N/A\nBUG_NUMBER:N/A\nFEATURE_AFFECTED:N/A\nOVERVIEW:N/A\nAdding the SVN log size requirement to the branch \n'], 'author': u'glv'}], [{'date': ['06-08-2012 09:01:52 PM'], 'path': [u'/branches/Patch_4_2_0_Branch'], 'msg': ['none', u'PATCH_BRANCH:N/A\nBUG_NUMBER:N/A\nFEATURE_AFFECTED:N/A\nOVERVIEW:N/A\nAdding the SVN log size requirement to the branch \n'], 'author': u'glv'}]]

更新:到目前为止,我可以将作者分组在一起,但由于某种原因,我不仅不能按字母顺序排列,甚至不能让作者成为列表中的第一个人,显示的内容类似于:

代码语言:javascript
复制
 Date: 06-08-2012 08:56:09 PM

  Changes by : glv

  Comments: PATCH_BRANCH:N/A BUG_NUMBER:N/A FEATURE_AFFECTED:N/A OVERVIEW:N/A Adding the svn commit line requrement  

            Directory Location: /trunk

我想要的排序方式更像这样。

代码语言:javascript
复制
  Changes by : glv
  Date: 06-08-2012 08:56:09 PM
  Directory Location: /trunk
  Comments: PATCH_BRANCH:N/A BUG_NUMBER:N/A FEATURE_AFFECTED:N/A OVERVIEW:N/A Adding the svn commit line requrement

我尝试了OrderedList,看看我是否可以让它以这种方式工作,但到目前为止,没有运气或成功。我是不是漏掉了什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-09-04 23:11:10

如果您只关心如何显示此信息以便于用户阅读,请使用pprint模块。

代码语言:javascript
复制
import pprint
pprint.pprint(author)

假设author是一个dict。或者,使用pprint.pformat获得一个字符串,您可以进一步操作/清理该字符串,例如,使用print pprint.pformat(author).replace(',','')删除逗号。

您还应该知道,dict不能被重新排序,因为它们本质上是一个哈希表,其关键字是哈希(就像一个集合)。

您也可以尝试使用collections.OrdererdDict

代码语言:javascript
复制
from collections import OrdererdDict
sorted_author = OrderedDict(sorted(author.iteritems()))

更新:奇怪的是,你仍然有这个问题。我只给你一些肯定会工作的代码,你可以从那里改编它:

代码语言:javascript
复制
def format_author(author):
    tups = sorted(author.iteritems())           # alphabetical sorting
    kmaxlen = max([len(k) for k, v in tups])    # for output alignment

    # some custom rearrangement. if there is a 'msg' key, we want it last
    tupkeys = [k for k, v in tups]
    if 'msg' in tupkeys:
        msg_tup = tups.pop(tupkeys.index('msg'))
        tups.append(msg_tup)    # append to the end
        # alternatively tups.insert(0, msg_tup) would insert at front

    output = []

    for k, v in tups:
        # dress our values
        if not v:
            v = ''
        elif isinstance(v, list):
            if len(v) == 1:
                v = v[0]
            if len(v) == 2 and v[0] in [None, 'none', 'None']:
                v = v[1]
         v = v.strip()
        output.append("%s: %s" % (k.rjust(kmaxlen), v))
    return "\n".join(output)

然后,您可以执行以下操作:

代码语言:javascript
复制
author = {'date': ['06-08-2012 09:01:52 PM'], 'path': [u'/branches/Patch_4_2_0_Branch'], 'author': u'glv', 'msg': ['none', u'blah blah blah \n']}
s = format_author(author)
print s

并获得如下输出:

代码语言:javascript
复制
author: glv
  date: 06-08-2012 09:01:52 PM
  path: /branches/Patch_4_2_0_Branch
   msg: blah blah blah
票数 2
EN

Stack Overflow用户

发布于 2012-09-05 00:24:56

您可以考虑为authorentry创建一个类,而不是使用dict并实现__str__方法。

代码语言:javascript
复制
class authorentry:
    # create authorentry; usage: x = authorentry(author, date, path, msg)
    def __init__(self, author, date, path, msg):
        self.author = author
        self.date = date
        self.path = path
        self.msg = msg
    # return string representation for authorentry
    def __str__(self):
        return "Authorentry(name: %s, date: %r, path: ...)" % (self.author, self.date, ...)

现在您可以创建并打印authorentry,如下所示:

代码语言:javascript
复制
ae = authorentry("some name", "some date", "some path", "some message")
print ae
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12266208

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档