38

I want to convert the following string into dictionary without using eval() function in Python 3.5.

d="{'Age': 7, 'Name': 'Manni'}";

Can anybody tell me the good way than using the eval() function?

What I really want is a function which can directly convert a dictionary to a string.

SuperStormer
  • 4,997
  • 5
  • 25
  • 35
arun chauhan
  • 664
  • 2
  • 6
  • 9

1 Answers1

86
  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}')
    
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • 4
    I was getting crazy on why `json.loads()` was not working for me. **Thanks** for that clarification. – Masclins May 23 '18 at 14:46
  • @DeepSpace can you tell why it's safer? I've noticed that it's quite CPU expensive as solution – Olfredos6 Nov 14 '18 at 11:59
  • 1
    @Olfredos6 It has nothing to do with CPU usage. `eval` is simply unsafe, especially when used with uncontrolled user input. See what happens if you execute `import os ; eval("os.remove('do_not_replace_with_a_valid_path')")`. On the other-hand, `literal_eval` will only work with, well, literals. `literal_eval("os.remove('do_not_replace_with_a_valid_path')")` outputs `ValueError: malformed node or string` – DeepSpace Nov 14 '18 at 14:28
  • @DeepSpace alright... – Olfredos6 Nov 14 '18 at 16:44