如何使字典中的每个键值对都在新的一行上打印?

33

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

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

如何使每个键值对都在新的一行上打印出来?

这是我用来获取这个字典的代码,虽然它很长。我基本上将每个键值对添加到了字典中。所以我找到了最短的单词,然后将其添加到了字典中。我也注意到有多余的冒号,但我认为这是值的一部分,我可以使用.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

请注意,您的键中似乎有一些多余的冒号。 我建议查看一下您用于生成该字典的任何操作。 - DSM
@DSM,我添加了生成字典的代码。 - user2976821
9个回答

43

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

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

稍作修改:逗号分隔符的位置必须扮演连接器的角色。print("{" + ",\n".join("{!r}: {!r}".format(k, v) for k, v in d.items()) + "}") - Shubham Singh
@ShubhamSingh 我不会说它“必须”是这样的 - 在Python中,尾随逗号是有效的(例如在JavaScript中也是如此,尽管在类似的JSON中不是)。 - jonrsharpe

27
你可能正在寻找标准库中提供的漂亮打印工具pprint。例如:
import pprint
pprint.pprint({'avglen': 4.419354838709677, 
               'count:': 93,
               'mosts:': 'your',
               'longs:': ['stretched'],
               'shorts:': ['i', 'a'],})

输出

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

10

遍历 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']

或使用pprint模块:

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

1
有没有一种方法可以在不导入任何内容的情况下完成它?第一个不返回字典。 - user2976821

10

如果您使用pprint,但仍然无法将每个条目打印到新行,请注意可能是字典条目或整个字典过短了。在这种情况下,直接调用PrettyPrinter类并根据文档中的说明设置width参数即可:

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

5
我发现了一种使用json的新方法,非常易于使用。
import json
dict1 = {'0': 0, '1': 70, '2': 37, '3': 11, '4': 6, '5': 5, '6': 3, '7': 1, '8': 0, '9': 0, '10': 0, '11': 0, '12': 0, '13': 0, '14': 0, '15': 0}
print(json.dumps(dict1, indent = 4))

结果应该像这样:
{
    "0": 0,
    "1": 70,
    "2": 37,
    "3": 11,
    "4": 6,
    "5": 5,
    "6": 3,
    "7": 1,
    "8": 0,
    "9": 0,
    "10": 0,
    "11": 0,
    "12": 0,
    "13": 0,
    "14": 0,
    "15": 0
}

以下是这个帖子中的第一个回答:

如何在Python中逐行打印字典?


4

如果您需要快速打印,可以使用字符串替换将换行符放入输出中。但是,如果字典包含列表,则此方法不会产生美观的结果;这些列表也会获得换行符。

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

输出

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

1

在你之前的六个问题中,你似乎将这个不好的字典作为一种文本索引对象使用。为什么不将它变成一个适当的类呢?

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

0
resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100, }


for key in resources:
    print (f"{key}: {resources[key]}")

输出

water: 300
milk: 200
coffee: 100

0
可以这样做,而无需导入任何模块。只需迭代字典并在每个键值对后打印一个新行即可。
dict = {'1':1,'2':2,'3':3}
for key,value in dict.items():
    print(key,value,'\n')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接