2

我正在研究python中的字典。我正在尝试按字母顺序对其进行排序并将其拆分以使其看起来更好一些。这是我迄今为止在字典中的代码。

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',如果可能的话。关于如何完成它的任何想法?

这就是我按原样打印时的样子。

我想要的是作者首先出现在列表中而不是日期。如果可能的话,我希望它按字母顺序排列,并删除条目中的逗号以更清晰地打印出来。是否可以?

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

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

 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

我希望它订购的方式更像这样。

  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 以查看是否可以让它以这种方式工作,但到目前为止还没有运气或成功。有什么我想念的吗?

4

2 回答 2

2

如果您只关心呈现这些信息以提高用户的可读性,请使用pprintmodule.

import pprint
pprint.pprint(author)

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

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

您也可以尝试使用collections.OrdererdDict

from collections import OrdererdDict
sorted_author = OrderedDict(sorted(author.iteritems()))

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

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)

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

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

并得到这样的输出:

author: glv
  date: 06-08-2012 09:01:52 PM
  path: /branches/Patch_4_2_0_Branch
   msg: blah blah blah
于 2012-09-04T15:11:10.247 回答
1

您可能会考虑创建一个类authorentry而不是使用 dict 并实现该__str__方法。

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

ae = authorentry("some name", "some date", "some path", "some message")
print ae
于 2012-09-04T16:24:55.670 回答