how to convert a sting to dictionary without knowing the string??

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Prasanti
    New Member
    • Apr 2019
    • 1

    how to convert a sting to dictionary without knowing the string??

    i m new to python ..so i have converted a list to dictionary ,as i know my sentence so easily i can convert ,,bt i want to knw how to convert tht list to dictionary when we didint kow the string..
  • Favevabj
    New Member
    • Apr 2019
    • 1

    #2
    1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval

    python_dict = literal_eval("{ 'a': 1}")
    2. json.loads but it would require your string to use double quotes:

    import json

    python_dict = json.loads('{"a ": 1}')

    Comment

    • Luuk
      Recognized Expert Top Contributor
      • Mar 2012
      • 1043

      #3
      First of all you keyboard needs to be renewed, some characters are missing.... 😉😉

      I am new to python too, maybe this code can help a bit?:
      Code:
      a='Type "help", "copyright", "credits" or "license" for more information.'
      c=1
      d={}
      for b in a.split():
        print(b)
        d[c]=b
        c=c+1
      After this 'd' contains a dictionary.

      For example 'd[2]' will contain the second word in the sentence.

      Comment

      Working...