Python 如何使字典的每个键值打印在新行上?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20181899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:47:58  来源:igfitidea点击:

how to make each key-value of a dictionary print on a new line?

pythonpython-3.xdictionary

提问by user2976821

If I have a given dictionary like this:

如果我有这样的给定字典:

{'avglen': 4.419354838709677, 'count:': 93, 'mosts:': 'your', 'longs:': ['stretched'], 'shorts:': ['i', 'a'],}

how do I make each key-value print on a new line?

如何在新行上打印每个键值?

well its long but here is the code I'm using to get this dictionary. I pretty much added each key-value to the dictionary. So i figured out the shortest word and then I added that to the dictionary. I noticed it too that there are extra colons. but I figured its part of the values and I can use .replace() to take it away??

好吧,它很长,但这是我用来获取这本字典的代码。我几乎将每个键值添加到字典中。所以我找出了最短的单词,然后将其添加到字典中。我也注意到有额外的冒号。但我想出了它的一部分价值,我可以用 .replace() 把它拿走??

def build_report(freq):
    report={}
    freq_list=list(freq.keys())
    keys=sorted(freq, key=len)
    #for shorts:
    shortest=keys[0]
    shortest = [keys[0]]
    for key in keys[1:]:
        if len(key) == len(shortest[0]):
            shortest.append(key)
        else:
            break   
    report["shorts:"]=shortest
    #for longs:
    longest=keys[-1]
    longest = [keys[-1]]
    for key in reversed(keys[:-1]):
        if len(key) == len(longest[0]):
            longest.append(key)
        else:
            break
    report["longs:"]=longest
    #for mode:
    val_list=list(freq.values())
    sorted_val_list=sorted(val_list)
    mode=sorted_val_list[-1]
    for key in freq.keys():
        if freq[key]==mode:
            mode_word=key
    report["mosts:"]=mode_word
    # for word count:
    wordcount=len(list(freq.keys()))
    report["count:"]=wordcount
    #for average length:
    avg=list(freq.keys())
    average=sum(map(len,avg))/len(avg)
    report["avglen"]=average
    #for freq dictionary of word to word count
    freqs=freq
    report["freqs:"]=freqs
    return report

采纳答案by jonrsharpe

If you really don't want to import pprint but want it to "look like" a dictionary, you could do:

如果你真的不想导入 pprint 但希望它“看起来像”一本字典,你可以这样做:

print("{" + "\n".join("{!r}: {!r},".format(k, v) for k, v in d.items()) + "}")

回答by Ashwini Chaudhary

Iterate over dict.itemsand print:

迭代dict.items并打印:

>>> d = {'avglen': 4.419354838709677, 'count:': 93, 'mosts:': 'your', 'longs:': ['stretched'], 'shorts:': ['i', 'a'],}
>>> for k, v in d.items():
...     print (k, '-->', v)
...     
mosts: --> your
count: --> 93
avglen --> 4.41935483871
shorts: --> ['i', 'a']
longs: --> ['stretched']

Or use the pprintmodule:

或者使用pprint模块:

>>> import pprint
>>> pprint.pprint(d)
{'avglen': 4.419354838709677,
 'count:': 93,
 'longs:': ['stretched'],
 'mosts:': 'your',
 'shorts:': ['i', 'a']}

回答by Nathan Davis

You may be looking for pprint, the pretty printer standard library. For example:

您可能正在寻找pprint,漂亮的打印机标准库。例如:

import pprint
pprint.pprint({'avglen': 4.419354838709677, 
               'count:': 93,
               'mosts:': 'your',
               'longs:': ['stretched'],
               'shorts:': ['i', 'a'],})

outputs

产出

{'avglen': 4.419354838709677,
 'count:': 93,
 'longs:': ['stretched'],
 'mosts:': 'your',
 'shorts:': ['i', 'a']}

回答by Hugh Bothwell

In your past six questions or so, you seem to be using this poor dictionary as a text-indexed object of sorts. Why not make it a proper class?

在您过去的六个左右的问题中,您似乎将这本糟糕的字典用作各种文本索引对象。为什么不让它成为一个合适的类呢?

from collections import Counter

textfreq = {
    'I': 1, 'heaven': 1, 'filled': 1, 'their': 1, 'termed': 1, 'of': 4,
    'And': 3, 'parts': 1, 'neer': 1, 'to': 2, 'song': 1, 'poets': 1,
    'The': 1, 'a': 2, 'were': 2, 'verse': 1, 'your': 6, 'knows': 1,
    'not': 1, 'half': 1, 'number': 1, 'but': 1, 'yours': 1, 'come': 2,
    'rage': 1, 'age': 2, 'Though': 1, 'men': 1, 'fresh': 1, 'heavenly': 1,
    'say': 1, 'alive': 1, 'truth': 1, 'this': 1, 'If': 2, 'than': 1,
    'old': 1, 'believe': 1, 'Which': 1, 'that': 1, 'You': 1, 'faces': 1,
    'yet': 1, 'poet': 1, 'in': 4, 'life': 1, 'most': 1, 'earthly': 1,
    'will': 1, 'hides': 1, 'my': 3, 'papers': 1, 'is': 1, 'stretched': 1,
    'rights': 1, 'eyes': 1, 'it': 3, 'yellowed': 1, 'Such': 1, 'So': 1,
    'all': 1, 'lies': 1, 'the': 1, 'an': 1, 'as': 1, 'write': 1,
    'child': 1, 'deserts': 1, 'shows': 1, 'tongue': 1, 'twice': 1,
    'Be': 1, 'high': 1, 'some': 1, 'could': 1, 'should': 2, 'and': 2,
    'touched': 1, 'like': 1, 'would': 1, 'Who': 1, 'tomb': 1, 'numbers': 1,
    'antique': 1, 'scorned': 1, 'metre': 1, 'time': 2, 'touches': 1,
    'be': 1, 'with': 2, 'true': 1, 'beauty': 1, 'rhyme': 1, 'less': 1,
    'But': 1, 'graces': 1, 'live': 1
}

class TextStats():
    def __init__(self, text=''):
        if hasattr(text, 'wordfreq'):
            # copy an existing TextStats object
            self.wordfreq = Counter(text.wordfreq)
        elif hasattr(text, 'keys'):
            # load from an existing dict or Counter
            self.wordfreq = Counter(text)
        else:
            # parse from a string
            # TO DO - strip all punctuation
            self.wordfreq = Counter(w for w in text.lower().split() if w)

    @classmethod
    def from_file(cls, fname):
        with open(fname) as inf:
            text = ' '.join(line.strip() for line in inf.readlines())
            return cls(text.translate(None, '`~!@#$\'"'))

    def __add__(self, otherTextStats):
        return TextStats(self.wordfreq + otherTextStats.wordfreq)

    def __str__(self):
        return(
           "Count:        {}\n"
           "Average len:  {:0.4f}\n"
           "Shortest:     {}\n"
           "Most common:  {}\n"
           "Longest:      {}\n".format(
               self.total_words,
               self.average_word_length,
               self.shortest_words,
               self.most_common_words,
               self.longest_words
           )
        )

    @property
    def unique_words(self):
        return len(self.wordfreq)

    @property
    def total_words(self):
        return sum(self.wordfreq.values())

    @property
    def total_letters(self):
        return sum(len(w)*c for w,c in self.wordfreq.items())

    @property
    def average_word_length(self):
        return float(self.total_letters) / self.total_words

    @property
    def shortest_words(self):
        minlen = len(min(self.wordfreq, key=len))
        return sorted(w for w in self.wordfreq if len(w)==minlen)

    @property
    def most_common_words(self):
        most_common = self.wordfreq.most_common()
        howmany = most_common[0][1] if most_common else 0
        return sorted(w for w,c in most_common if c == howmany)

    @property
    def longest_words(self):
        maxlen = len(max(self.wordfreq, key=len))
        return sorted(w for w in self.wordfreq if len(w)==maxlen)

def main():
    t = TextStats(textfreq)
    u = TextStats.from_file('corpus.txt')
    v = t + u

    print(t)
    print()
    print(u)
    print()
    print(v)

if __name__=="__main__":
    main()

回答by mluerig

for those of you using pprintwondering why your dictionary still wont print each entry to a new line: could be that your dictionary entries or the whole dictionary are too short. in this case, invoke the PrettyPrinterclass directly and set the widthargument accordingly, as specified in the docs:

对于那些pprint想知道为什么您的字典仍然不会将每个条目打印到新行的人:可能是您的字典条目或整个字典太短了。在这种情况下,PrettyPrinter直接调用类并相应地设置width参数,如文档中所述:

import pprint
stuff = {'avglen': 4.41, 'count:': 93, 'shorts:': ['i', 'a']}
pretty = pprint.PrettyPrinter(width=30)
pretty.pprint(stuff)

回答by MrBlank

For a quick print you could use string replace to put newlines into the output. This method does not give beautiful results if the dictionary contains lists; those lists will also get newlines.

为了快速打印,您可以使用字符串替换将换行符放入输出中。如果字典包含列表,此方法不会给出漂亮的结果;这些列表也将获得换行符。

td = {'avglen': 4.419354838709677, 'count:': 93, 'mosts:': 'your', 'longs:': ['stretched'], 'shorts:': ['i', 'a'],}
print(str(td).replace(', ',',\n '))

Outputs

输出

{'avglen': 4.419354838709677,
 'count:': 93,
 'mosts:': 'your',
 'longs:': ['stretched'],
 'shorts:': ['i',
 'a']}