programing

파이썬에서 사전을 멋지게 출력하는 방법?

mailnote 2023. 9. 8. 21:39
반응형

파이썬에서 사전을 멋지게 출력하는 방법?

저는 이제 막 파이썬을 배우기 시작했고 텍스트 게임을 만들고 있습니다.인벤토리 시스템을 원하지만, 보기 흉하게 보이지 않으면 사전을 출력할 수 없을 것 같습니다.

이것이 지금까지 제가 가진 것입니다.

def inventory():
    for numberofitems in len(inventory_content.keys()):
        inventory_things = list(inventory_content.keys())
        inventory_amounts = list(inventory_content.values())
        print(inventory_things[numberofitems])

파이썬에 포함된 모듈(예쁜 프린트)이 마음에 듭니다.개체를 인쇄하거나 멋진 문자열 버전의 형식을 지정하는 데 사용할 수 있습니다.

import pprint

# Prints the nicely formatted dictionary
pprint.pprint(dictionary)

# Sets 'pretty_dict_str' to the formatted string value
pretty_dict_str = pprint.pformat(dictionary)

그러나 인벤토리를 인쇄하는 것처럼 들립니다. 사용자는 다음과 같은 것으로 표시하기를 원할 것입니다.

def print_inventory(dct):
    print("Items held:")
    for item, amount in dct.items():  # dct.iteritems() in Python 2
        print("{} ({})".format(item, amount))

inventory = {
    "shovels": 3,
    "sticks": 2,
    "dogs": 1,
}

print_inventory(inventory)

인쇄하는 항목:

Items held:
shovels (3)
sticks (2)
dogs (1)

내가 가장 좋아하는 방법:

import json
print(json.dumps(dictionary, indent=4, sort_keys=True))

제가 사용할 원라이너는 여기 있습니다. (편집: JSON 직렬화가 불가능한 것에도 적용됨)

print("\n".join("{}\t{}".format(k, v) for k, v in dictionary.items()))

설명:이는 사전의 키와 값을 반복하여 키 + 탭 + 값과 같은 형식화된 문자열을 생성하며, 각각에 대해 키 + 탭 + 값과 같은 형식화된 문자열을 생성합니다."\n".join(...모든 문자열 사이에 새 줄을 배치하여 새 문자열을 만듭니다.

예:

>>> dictionary = {1: 2, 4: 5, "foo": "bar"}
>>> print("\n".join("{}\t{}".format(k, v) for k, v in dictionary.items()))
1   2
4   5
foo bar
>>>

편집 2: 여기 분류된 버전이 있습니다.

"\n".join("{}\t{}".format(k, v) for k, v in sorted(dictionary.items(), key=lambda t: str(t[0])))

pprint 대신 bipprint를 사용하는 것을 제안합니다.

예:

인쇄물

{'entities': {'hashtags': [],
              'urls': [{'display_url': 'github.com/panyanyany/beeprint',
                        'indices': [107, 126],
                        'url': 'https://github.com/panyanyany/beeprint'}],
              'user_mentions': []}}

비프린트

{
  'entities': {
    'hashtags': [],
    'urls': [
      {
        'display_url': 'github.com/panyanyany/beeprint',
        'indices': [107, 126],
        'url': 'https://github.com/panyanyany/beeprint'}],
      },
    ],
    'user_mentions': [],
  },
}

Yaml은 일반적으로 훨씬 더 가독성이 뛰어납니다. 특히 복잡한 중첩 개체, 계층 구조, 중첩 사전 등이 있는 경우 더욱 그렇습니다.

먼저 pyaml 모듈이 있는지 확인합니다.

pip install pyyaml

그리고나서,

import yaml
print(yaml.dump(my_dict))

Python 3.6 이후로 f-strings를 사용하여 @sudo의 원-라이너를 더욱 압축적으로 작성할 수 있습니다.

print("\n".join(f"{k}\t{v}" for k, v in dictionary.items()))

간단한 사전을 인쇄하기 위해 이 기능을 썼습니다.

def dictToString(dict):
  return str(dict).replace(', ','\r\n').replace("u'","").replace("'","")[1:-1]

동의합니다, "착하게"는 매우 주관적입니다.이게 도움이 되는지 확인해보세요. 제가 dict를 디버그하는 데 사용해왔던 것입니다.

for i in inventory_things.keys():
    logger.info('Key_Name:"{kn}", Key_Value:"{kv}"'.format(kn=i, kv=inventory_things[i]))

(Python 3에서) 함수를 만들었습니다.

def print_dict(dict):
    print(

    str(dict)
    .replace(', ', '\n')
    .replace(': ', ':\t')
    .replace('{', '')
    .replace('}', '')

    )

모든 필요에 맞지는 않지만 시도해보니 좋은 포맷의 출력이 나왔습니다. 그래서 사전을 Dataframe으로 변환하면 거의 다 됩니다.

pd.DataFrame(your_dic.items())

열을 정의하여 가독성을 높일 수도 있습니다.

pd.DataFrame(your_dic.items(),columns={'Value','key'})

그러니 한 번 해보세요.

print(pd.DataFrame(your_dic.items(),columns={'Value','key'}))

언급URL : https://stackoverflow.com/questions/44689546/how-to-print-out-a-dictionary-nicely-in-python

반응형