Converting a string to dictionary in Python Value Error









up vote
0
down vote

favorite












I have tried different options to convert a string to dictionary.



My string looks like this:



'severity_label': 'Major', 'ne_reported_time': 1475424546, 'node_id': 54357, 'prob_cause_string': None


When i use



 a_dict = dict([x.strip('').split(":"),]) 


it gives me an error:



Traceback (most recent call last):
File "<pyshell#168>", line 1, in <module>
a_dict = dict([x.strip('').split(":"),])
ValueError: dictionary update sequence element #0 has length 121; 2 is required


I am running this on Python3. Also tried various other options things not working. Any help appreciated.










share|improve this question



















  • 1




    You got the right answer (using ast.literal_eval()) but you should really consider why you have a Python dictionary string representation in the first place. That is not a sane format to pass around information. Better use JSON or any other standard format. Or at least pickled data, as that is meant to be a serialization format.
    – BlackJack
    Feb 4 '16 at 15:20














up vote
0
down vote

favorite












I have tried different options to convert a string to dictionary.



My string looks like this:



'severity_label': 'Major', 'ne_reported_time': 1475424546, 'node_id': 54357, 'prob_cause_string': None


When i use



 a_dict = dict([x.strip('').split(":"),]) 


it gives me an error:



Traceback (most recent call last):
File "<pyshell#168>", line 1, in <module>
a_dict = dict([x.strip('').split(":"),])
ValueError: dictionary update sequence element #0 has length 121; 2 is required


I am running this on Python3. Also tried various other options things not working. Any help appreciated.










share|improve this question



















  • 1




    You got the right answer (using ast.literal_eval()) but you should really consider why you have a Python dictionary string representation in the first place. That is not a sane format to pass around information. Better use JSON or any other standard format. Or at least pickled data, as that is meant to be a serialization format.
    – BlackJack
    Feb 4 '16 at 15:20












up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have tried different options to convert a string to dictionary.



My string looks like this:



'severity_label': 'Major', 'ne_reported_time': 1475424546, 'node_id': 54357, 'prob_cause_string': None


When i use



 a_dict = dict([x.strip('').split(":"),]) 


it gives me an error:



Traceback (most recent call last):
File "<pyshell#168>", line 1, in <module>
a_dict = dict([x.strip('').split(":"),])
ValueError: dictionary update sequence element #0 has length 121; 2 is required


I am running this on Python3. Also tried various other options things not working. Any help appreciated.










share|improve this question















I have tried different options to convert a string to dictionary.



My string looks like this:



'severity_label': 'Major', 'ne_reported_time': 1475424546, 'node_id': 54357, 'prob_cause_string': None


When i use



 a_dict = dict([x.strip('').split(":"),]) 


it gives me an error:



Traceback (most recent call last):
File "<pyshell#168>", line 1, in <module>
a_dict = dict([x.strip('').split(":"),])
ValueError: dictionary update sequence element #0 has length 121; 2 is required


I am running this on Python3. Also tried various other options things not working. Any help appreciated.







python python-3.x






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Feb 4 '16 at 12:18









JBernardo

22.3k56095




22.3k56095










asked Feb 4 '16 at 11:25









Praveeda

12




12







  • 1




    You got the right answer (using ast.literal_eval()) but you should really consider why you have a Python dictionary string representation in the first place. That is not a sane format to pass around information. Better use JSON or any other standard format. Or at least pickled data, as that is meant to be a serialization format.
    – BlackJack
    Feb 4 '16 at 15:20












  • 1




    You got the right answer (using ast.literal_eval()) but you should really consider why you have a Python dictionary string representation in the first place. That is not a sane format to pass around information. Better use JSON or any other standard format. Or at least pickled data, as that is meant to be a serialization format.
    – BlackJack
    Feb 4 '16 at 15:20







1




1




You got the right answer (using ast.literal_eval()) but you should really consider why you have a Python dictionary string representation in the first place. That is not a sane format to pass around information. Better use JSON or any other standard format. Or at least pickled data, as that is meant to be a serialization format.
– BlackJack
Feb 4 '16 at 15:20




You got the right answer (using ast.literal_eval()) but you should really consider why you have a Python dictionary string representation in the first place. That is not a sane format to pass around information. Better use JSON or any other standard format. Or at least pickled data, as that is meant to be a serialization format.
– BlackJack
Feb 4 '16 at 15:20












4 Answers
4






active

oldest

votes

















up vote
1
down vote













Actually this is not JSON. This is a representation of a python object (like using the repr function).



The most safe way to convert this back to a python object is to use the ast.literal_eval function.






share|improve this answer



























    up vote
    0
    down vote













    You should use json.loads



    import json
    a = '"severity_label": "Major", "ne_reported_time": 1475424546, "node_id": 54357, "prob_cause_string": null'
    d = json.loads(a)


    Note I replaced ' by " and None by null






    share|improve this answer





























      up vote
      0
      down vote













      Why not to use Python 3's inbuilt ast library's function literal_eval. It is better to use literal_eval instead of eval



      import ast
      str_of_dict = "'key1': 'key1value', 'key2': 'key2value'"
      ast.literal_eval(str_of_dict)


      will give output as actual Dictionary



      'key1': 'key1value', 'key2': 'key2value'


      This is easy as you like.






      share|improve this answer



























        up vote
        -1
        down vote













        That string really is valid JSON, I think. Just use the json.loads functionality to get a dictionary.






        share|improve this answer




















          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f35199735%2fconverting-a-string-to-dictionary-in-python-value-error%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote













          Actually this is not JSON. This is a representation of a python object (like using the repr function).



          The most safe way to convert this back to a python object is to use the ast.literal_eval function.






          share|improve this answer
























            up vote
            1
            down vote













            Actually this is not JSON. This is a representation of a python object (like using the repr function).



            The most safe way to convert this back to a python object is to use the ast.literal_eval function.






            share|improve this answer






















              up vote
              1
              down vote










              up vote
              1
              down vote









              Actually this is not JSON. This is a representation of a python object (like using the repr function).



              The most safe way to convert this back to a python object is to use the ast.literal_eval function.






              share|improve this answer












              Actually this is not JSON. This is a representation of a python object (like using the repr function).



              The most safe way to convert this back to a python object is to use the ast.literal_eval function.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Feb 4 '16 at 12:16









              JBernardo

              22.3k56095




              22.3k56095






















                  up vote
                  0
                  down vote













                  You should use json.loads



                  import json
                  a = '"severity_label": "Major", "ne_reported_time": 1475424546, "node_id": 54357, "prob_cause_string": null'
                  d = json.loads(a)


                  Note I replaced ' by " and None by null






                  share|improve this answer


























                    up vote
                    0
                    down vote













                    You should use json.loads



                    import json
                    a = '"severity_label": "Major", "ne_reported_time": 1475424546, "node_id": 54357, "prob_cause_string": null'
                    d = json.loads(a)


                    Note I replaced ' by " and None by null






                    share|improve this answer
























                      up vote
                      0
                      down vote










                      up vote
                      0
                      down vote









                      You should use json.loads



                      import json
                      a = '"severity_label": "Major", "ne_reported_time": 1475424546, "node_id": 54357, "prob_cause_string": null'
                      d = json.loads(a)


                      Note I replaced ' by " and None by null






                      share|improve this answer














                      You should use json.loads



                      import json
                      a = '"severity_label": "Major", "ne_reported_time": 1475424546, "node_id": 54357, "prob_cause_string": null'
                      d = json.loads(a)


                      Note I replaced ' by " and None by null







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Feb 4 '16 at 11:29









                      Marcus Müller

                      23.2k32267




                      23.2k32267










                      answered Feb 4 '16 at 11:29









                      Benjamin

                      1,215727




                      1,215727




















                          up vote
                          0
                          down vote













                          Why not to use Python 3's inbuilt ast library's function literal_eval. It is better to use literal_eval instead of eval



                          import ast
                          str_of_dict = "'key1': 'key1value', 'key2': 'key2value'"
                          ast.literal_eval(str_of_dict)


                          will give output as actual Dictionary



                          'key1': 'key1value', 'key2': 'key2value'


                          This is easy as you like.






                          share|improve this answer
























                            up vote
                            0
                            down vote













                            Why not to use Python 3's inbuilt ast library's function literal_eval. It is better to use literal_eval instead of eval



                            import ast
                            str_of_dict = "'key1': 'key1value', 'key2': 'key2value'"
                            ast.literal_eval(str_of_dict)


                            will give output as actual Dictionary



                            'key1': 'key1value', 'key2': 'key2value'


                            This is easy as you like.






                            share|improve this answer






















                              up vote
                              0
                              down vote










                              up vote
                              0
                              down vote









                              Why not to use Python 3's inbuilt ast library's function literal_eval. It is better to use literal_eval instead of eval



                              import ast
                              str_of_dict = "'key1': 'key1value', 'key2': 'key2value'"
                              ast.literal_eval(str_of_dict)


                              will give output as actual Dictionary



                              'key1': 'key1value', 'key2': 'key2value'


                              This is easy as you like.






                              share|improve this answer












                              Why not to use Python 3's inbuilt ast library's function literal_eval. It is better to use literal_eval instead of eval



                              import ast
                              str_of_dict = "'key1': 'key1value', 'key2': 'key2value'"
                              ast.literal_eval(str_of_dict)


                              will give output as actual Dictionary



                              'key1': 'key1value', 'key2': 'key2value'


                              This is easy as you like.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 11 at 15:16









                              FightWithCode

                              295




                              295




















                                  up vote
                                  -1
                                  down vote













                                  That string really is valid JSON, I think. Just use the json.loads functionality to get a dictionary.






                                  share|improve this answer
























                                    up vote
                                    -1
                                    down vote













                                    That string really is valid JSON, I think. Just use the json.loads functionality to get a dictionary.






                                    share|improve this answer






















                                      up vote
                                      -1
                                      down vote










                                      up vote
                                      -1
                                      down vote









                                      That string really is valid JSON, I think. Just use the json.loads functionality to get a dictionary.






                                      share|improve this answer












                                      That string really is valid JSON, I think. Just use the json.loads functionality to get a dictionary.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Feb 4 '16 at 11:29









                                      Marcus Müller

                                      23.2k32267




                                      23.2k32267



























                                          draft saved

                                          draft discarded
















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.





                                          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                          Please pay close attention to the following guidance:


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f35199735%2fconverting-a-string-to-dictionary-in-python-value-error%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          這個網誌中的熱門文章

                                          Barbados

                                          How to read a connectionString WITH PROVIDER in .NET Core?

                                          Node.js Script on GitHub Pages or Amazon S3