简体   繁体   English

如何在python字典中存储和检索多行值

[英]how to store and retrieve multi-line value in python dictionary

I want to use dictionary in python of following type 我想在以下类型的python中使用字典

dictionary = {  
  "Who is Elon Musk":  
    "Elon Reeve Musk FRS is an American business magnate, investor and engineer. He is the founder, CEO, and lead designer of SpaceX; co-founder, CEO, and product architect of Tesla, Inc.; and co-founder and CEO of Neuralink " ,   
  "Second Question":  
    "Second answer"  
}

I want to retrieve the answer from question by using above approach. 我想通过使用上述方法从问题中检索答案。
What is wrong with this approach and what are correct ways of doing it. 这种方法有什么问题,什么是正确的方法。 Also is there any better way than using dictionary to perform above task. 还有什么比使用字典执行上述任务更好的方法了。

You can use a newline character "\\n" to show where a line break should occur. 您可以使用换行符"\\n"来显示换行符应在何处发生。 Consecutive string literals are interpreted as a single string, so we can easily break the literal in the same place as the final string will be broken. 连续字符串文字被解释为单个字符串,因此我们可以轻松地将文字拆分为最终字符串将被破坏的位置。

dictionary = {  
  "Who is Elon Musk":  
    "Elon Reeve Musk FRS is an American business magnate, investor and engineer.\n"
    "He is the founder, CEO, and lead designer of SpaceX;\n"
    "co-founder, CEO, and product architect of Tesla, Inc.;\n"
    "and co-founder and CEO of Neuralink." ,   
  "Second Question":  
    "Second answer"  
}

A triple-quoted string could work here, but they don't play nice with Python's indentation rules, making code difficult to read. 用三引号引起来的字符串可以在这里工作,但是它们不能很好地配合Python的缩进规则,使代码难以阅读。

Dictionaries are usually for data which can be structured as key-value pairs. 字典通常用于可构造为键值对的数据。 In this case, it assumes that you know the exact question in order to look up the answer (is this really a good idea?). 在这种情况下,它假定您知道确切的问题才能查找答案(这真的是个好主意吗?)。 What about using a set? 那用一套呢? It prevents duplicates as well. 它还可以防止重复。

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

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