简体   繁体   English

如何在没有换行符 '\n' 的情况下打印字典值?

[英]How can I print dictionary value without newline '\n' character?

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)

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

I think that I know your problem, you can print it this way: define a dictionary as student_score :我想我知道你的问题,你可以这样打印:将字典定义为student_score

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

the output looks like this: output 看起来像这样:

Sam  :  7
John  :  10
Aadi  :  8

All you have to do is use a for loop to iterate through the dictionary.您所要做的就是使用 for 循环遍历字典。

As far as I know, python automatically translates \n to the proper newline character.据我所知,python 会自动将\n转换为正确的换行符。

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.您可以添加\t以进行额外的缩进。

Is there any other way instead of iterating the dictionary first and then printing there values separately?有没有其他方法可以先迭代字典然后单独打印值?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM