Programing

키로 정렬 된 파이썬 dict ()를 읽기 쉽게 출력

crosscheck 2020. 10. 19. 07:45
반응형

키로 정렬 된 파이썬 dict ()를 읽기 쉽게 출력


PrettyPrinter (인간 가독성을 위해)를 사용하여 파이썬 사전을 파일로 인쇄하고 싶지만 가독성을 더 높이기 위해 출력 파일의 키별로 사전을 정렬하도록하고 싶습니다. 그래서:

mydict = {'a':1, 'b':2, 'c':3}
pprint(mydict)

현재 인쇄

{'b':2,
 'c':3,
 'a':1}

사전을 PrettyPrint하고 싶지만 키별로 정렬하여 인쇄했습니다.

{'a':1,
 'b':2,
 'c':3}

이를 수행하는 가장 좋은 방법은 무엇입니까?


실제로 pprint는 python2.5에서 키를 정렬하는 것 같습니다.

>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
 'b': 9,
 'c': 8,
 'd': 7,
 'e': 6,
 'f': 5,
 'g': 4,
 'h': 3,
 'i': 2,
 'j': 1,
 'k': 0}

그러나 항상 파이썬 2.4에서는 아닙니다.

>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
 'b': 9,
 'c': 8,
 'd': 7,
 'e': 6,
 'f': 5,
 'g': 4,
 'h': 3,
 'i': 2,
 'j': 1,
 'k': 0}
>>> 

pprint.py (2.5)의 소스 코드를 읽으면 다음을 사용하여 사전을 정렬합니다.

items = object.items()
items.sort()

여러 줄의 경우 또는 단일 줄의 경우

for k, v in sorted(object.items()):

인쇄를 시도하기 전에 사전이 제대로 정렬되면 제대로 인쇄해야합니다. 2.4에서는 두 번째 sorted ()가 누락되었으므로 (당시 존재하지 않음) 한 줄에 인쇄 된 객체가 정렬되지 않습니다.

따라서 대답은 python2.5를 사용하는 것으로 보이지만 질문에서 출력을 설명하지는 못합니다.

Python3 업데이트

정렬 된 키로 예쁜 인쇄 (람다 x : x [0]) :

for key, value in sorted(dict_example.items(), key=lambda x: x[0]): 
    print("{} : {}".format(key, value))

정렬 된 으로 예쁜 인쇄 (람다 x : x [1]) :

for key, value in sorted(dict_example.items(), key=lambda x: x[1]): 
    print("{} : {}".format(key, value))

또 다른 대안 :

>>> mydict = {'a':1, 'b':2, 'c':3}
>>> import json

그런 다음 python2 :

>>> print json.dumps(mydict, indent=4, sort_keys=True) # python 2
{
    "a": 1, 
    "b": 2, 
    "c": 3
}

또는 파이썬 3 :

>>> print(json.dumps(mydict, indent=4, sort_keys=True)) # python 3
{
    "a": 1, 
    "b": 2, 
    "c": 3
}

Python pprint모듈은 실제로 이미 키로 사전을 정렬합니다. Python 2.5 이전 버전에서는 예쁘게 인쇄 된 표현이 여러 줄에 걸쳐있는 사전에서만 정렬이 트리거되었지만 2.5.X 및 2.6.X에서는 모든 사전이 정렬되었습니다.

Generally, though, if you're writing data structures to a file and want them human-readable and writable, you might want to consider using an alternate format like YAML or JSON. Unless your users are themselves programmers, having them maintain configuration or application state dumped via pprint and loaded via eval can be a frustrating and error-prone task.


An easy way to print the sorted contents of the dictionary, in Python 3:

>>> 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

The expression dict_example.items() returns tuples, which can then be sorted by sorted():

>>> dict_example.items()
dict_items([('c', 1), ('b', 2), ('a', 3)])
>>> sorted(dict_example.items())
[('a', 3), ('b', 2), ('c', 1)]

Below is an example to pretty print the sorted contents of a Python dictionary's values.

for key, value in sorted(dict_example.items(), key=lambda d_values: d_values[1]): 
    print("{} : {}".format(key, value))

I wrote the following function to print dicts, lists, and tuples in a more readable format:

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

Example usage in iPython:

>>> 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)

I had the same problem you had. I used a for loop with the sorted function passing in the dictionary like so:

for item in sorted(mydict):
    print(item)

You could transform this dict a little to ensure that (as dicts aren't kept sorted internally), e.g.

pprint([(key, mydict[key]) for key in sorted(mydict.keys())])

참고URL : https://stackoverflow.com/questions/1479649/readably-print-out-a-python-dict-sorted-by-key

반응형