0

Let's say this is my dictionary.

d = {"id": 12345, "msg": "Some msgs \n from the \n text file"}

I want to print this dictionary as:

>>> print(d)
{
"id": 12345,
"msg": "Some msgs
        from the
        text file"
}

How can I achieve this?

Also, I'm not able to return a string with newline characters into a formatted string. Let's say below is my string:

str = "Some msgs \n from the \n text file"

On printing it, I'll get formatted string:

>>> print(str)
Some msgs
from the
text file

But how can I make below code work similarly to print formatted dictionary?

d["msg"] = str
print(d)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Darshan
  • 352
  • 8
  • 24

3 Answers3

0

I think in this case you would have to loop over the dictionary elements, and print them as keys and values

for k,v in d.items():
    print('"{0}": {1}'.format(k, v))
Sri
  • 2,281
  • 2
  • 17
  • 24
0

I think that I know your problem, you can print it this way: define a dictionary as student_score:

for key, value in student_score.items():
    print(key, ' : ', value)

the output looks like this:

Sam  :  7
John  :  10
Aadi  :  8

All you have to do is use a for loop to iterate through the dictionary.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

As far as I know, python automatically translates \n to the proper newline character.

d = {"id": 12345, "msg": "Some msgs \n from the \n text file"}
for i in d:
    print ('"{0}": {1}'.format(i, d[i]))

and you can add \t for additional indentation.

Avishka Dambawinna
  • 1,180
  • 1
  • 13
  • 29