首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >以可读的方式打印出按键排序的python dict()

以可读的方式打印出按键排序的python dict()
EN

Stack Overflow用户
提问于 2009-09-25 21:22:12
回答 6查看 156.7K关注 0票数 87

我想使用PrettyPrinter将python字典打印到一个文件中(为了便于阅读),但为了进一步提高可读性,我在输出文件中按键对字典进行了排序。所以:

代码语言:javascript
复制
mydict = {'a':1, 'b':2, 'c':3}
pprint(mydict)

当前打印到

代码语言:javascript
复制
{'b':2,
 'c':3,
 'a':1}

我想把字典打印出来,但要按关键字PrettyPrint。

代码语言:javascript
复制
{'a':1,
 'b':2,
 'c':3}

做这件事最好的方法是什么?

EN

回答 6

Stack Overflow用户

发布于 2016-03-31 22:32:36

另一种替代方案:

代码语言:javascript
复制
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> import json

然后使用python2:

代码语言:javascript
复制
>>> print json.dumps(mydict, indent=4, sort_keys=True) # python 2
{
    "a": 1, 
    "b": 2, 
    "c": 3
}

或者使用python 3:

代码语言:javascript
复制
>>> print(json.dumps(mydict, indent=4, sort_keys=True)) # python 3
{
    "a": 1, 
    "b": 2, 
    "c": 3
}
票数 24
EN

Stack Overflow用户

发布于 2013-08-14 05:07:44

在Python 3中,有一种打印字典排序内容的简单方法:

代码语言:javascript
复制
>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> for key, value in sorted(dict_example.items()):
...   print("{} : {}".format(key, value))
... 
a : 3
b : 2
c : 1

表达式dict_example.items()返回元组,然后可以按sorted()对其进行排序

代码语言:javascript
复制
>>> dict_example.items()
dict_items([('c', 1), ('b', 2), ('a', 3)])
>>> sorted(dict_example.items())
[('a', 3), ('b', 2), ('c', 1)]

下面是一个很好地打印Python字典值的排序内容的示例。

代码语言:javascript
复制
for key, value in sorted(dict_example.items(), key=lambda d_values: d_values[1]): 
    print("{} : {}".format(key, value))
票数 14
EN

Stack Overflow用户

发布于 2012-08-03 11:51:19

我编写了以下函数,以便以更易读的格式打印字典、列表和元组:

代码语言:javascript
复制
def printplus(obj):
    """
    Pretty-prints the object passed in.

    """
    # Dict
    if isinstance(obj, dict):
        for k, v in sorted(obj.items()):
            print u'{0}: {1}'.format(k, v)

    # List or tuple            
    elif isinstance(obj, list) or isinstance(obj, tuple):
        for x in obj:
            print x

    # Other
    else:
        print obj

iPython中的用法示例:

代码语言:javascript
复制
>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> printplus(dict_example)
a: 3
b: 2
c: 1

>>> tuple_example = ((1, 2), (3, 4), (5, 6), (7, 8))
>>> printplus(tuple_example)
(1, 2)
(3, 4)
(5, 6)
(7, 8)
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1479649

复制
相关文章

相似问题

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