Reputation: 126
I want to have each pair (key, value) printed on a separate line from this list comprehension,
print({'Doc. ' + k + '.txt: ':v for k, v in dict.items()})
Such as:
{'Doc. 23.txt: ': 0.027716832767124815,
'Doc. 7.txt: ': 0.016852886586198594,
'Doc. 17.txt: ': 0.014667013392619908,
'Doc. 37.txt: ': 0.01410963740876677}
I tried concatenating '\n', which has no effect here. Thanks for any assistance.
P.S: Using pprint()
will disturb the order of the values which is unaffordable.
Upvotes: 0
Views: 572
Reputation: 1858
Dictionaries have no order, so if you want keys sorted as [23, 7, 17, 37]
, you could do something like:
>>> import json
>>> from collections import OrderedDict
>>>
>>> order = ["23", "7", "17", "37"]
>>> d = {
... "23": 0.0277,
... "7": 0.0168,
... "17": 0.0146,
... "37": 0.0141
... }
>>> sorted_d = OrderedDict([("Doc." + k + ".txt:", d[k]) for k in order])
>>> print(json.dumps(sorted_d, indent=4))
{
"Doc.23.txt:": 0.0277,
"Doc.7.txt:": 0.0168,
"Doc.17.txt:": 0.0146,
"Doc.37.txt:": 0.0141
}
Upvotes: 1
Reputation: 2406
Do you want something like this?
mydict = {23: 0.027716832767124815,
7: 0.016852886586198594,
17: 0.014667013392619908,
37: 0.01410963740876677}
print('{' + ',\n'.join(
["'Doc. {}.txt': {}".format(k, v) for k, v in mydict.items()]
) + '}')
Pay attention to the square brackets inside the print. They denote list comprehension (while curly brackets are dictionary comprehension). In this code, you can replace list comprehension with generator comprehension (round brackets), with the same end result.
',\n'.join(list)
inserts ',\n'
between the elements of the list, providing the result you asked for.
Upvotes: 1
Reputation: 7045
You could make your own print/format function just for this:
def my_print_function(d, prefix="", suffix=""):
print("{", end="")
for i, (k, v) in enumerate(d.items()):
if i == 0:
print("'{}{}{}': {},".format(prefix, k, suffix, v))
else:
print(" '{}{}{}': {},".format(prefix, k, suffix, v))
print("}")
my_print_function(my_dict, "Doc. ", ".txt: ")
# {'Doc. 23.txt: ': 0.027716832767124815,
# 'Doc. 7.txt: ': 0.016852886586198594,
# 'Doc. 17.txt: ': 0.014667013392619908,
# 'Doc. 37.txt: ': 0.01410963740876677,
# }
As far as I am aware, you won't be able to do this with a comprehension. Also, you should avoid naming things dict
as this overwrites the dict
constructor.
Upvotes: 1