Skip to content
Advertisement

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

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

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

Advertisement

Answer

If you really don’t want to import pprint but want it to “look like” a dictionary, you could do:

print("{" + "n".join("{!r}: {!r},".format(k, v) for k, v in d.items()) + "}")
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement