1

I want to use dictionary in python of following type

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.

Aditya
  • 37
  • 10
  • You could consider just using a 2D table where one column/row is questions and one is answers. It might be a bit faster and would keep the order. – Jay Calamari Jun 29 '18 at 18:23
  • 3
    Use triple quotes. Refer to multiline strings in python, which has lot of answers already in SO. – bluesmonk Jun 29 '18 at 18:26
  • multiline strings are no different from one line strings. Can you explain why triple quotes won't work? `print`ing it should give you a multiline paragraph just the way it was stored. It will only look different on the command line due to how \_\_repr\_\_ is implemented for strings – avigil Jun 29 '18 at 18:59
  • @AdityaAryan please explain why triple quotes don't work. Provide a MCVE, otherwise it is a question regarding multiline strings which has been answered already. – bluesmonk Jun 29 '18 at 21:08
  • @bluesmonk Triple quotes are working. I had some issue with the indentation as it is pointed out in the accepted answer. But this question should not be marked duplicate as it ask suggestion about other approaches for the given scenario. – Aditya Jun 30 '18 at 05:45

2 Answers2

2

You can use a newline character "\n" to show where a line break should occur. 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.

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
0

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.

robertt
  • 1
  • 1