User Tools

Site Tools


convert_a_string_to_a_dictionary

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
convert_a_string_to_a_dictionary [2023/02/26 03:10] – created rajuconvert_a_string_to_a_dictionary [2023/02/26 03:28] (current) – [ast.literaleval] raju
Line 1: Line 1:
 ===== Convert a string to a dictionary ===== ===== Convert a string to a dictionary =====
  
 +==== ast.literaleval ====
 You can use ast.literaleval from the ast (Abstract Syntax Trees) module. You can use ast.literaleval from the ast (Abstract Syntax Trees) module.
  
Line 28: Line 29:
  
 See also: See also:
-  * https://docs.python.org/3/library/ast.html#ast.literal_eval - documentation on ast.literal_eval 
   * https://stackoverflow.com/questions/988228/convert-a-string-representation-of-a-dictionary-to-a-dictionary - where I got the answer from   * https://stackoverflow.com/questions/988228/convert-a-string-representation-of-a-dictionary-to-a-dictionary - where I got the answer from
  
- +==== json.loads ==== 
-Another approach is to use json.loads . But its decoder wants double quotes around keys and values.+Another approach is to use json.loads . But its decoder wants double quotes around strings.
 <code> <code>
-In [4]:+In [1]:
 s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
 +
 +
 +In [2]:
 import json import json
-json.loads(s.replace("'", "\"")) +json.loads(s) 
-Out[4]:+... 
 +JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) 
 +</code> 
 + 
 +One workaround is to replace single quotes with double quotes 
 +<code> 
 +In [3]: 
 +s2 = s.replace("'", "\"") 
 +json.loads(s2
 +Out[3]:
 {'muffin': 'lolz', 'foo': 'kitty'} {'muffin': 'lolz', 'foo': 'kitty'}
  
-In [5]: +In [4]: 
-type(json.loads(s.replace("'", "\""))) +type(json.loads(s2)) 
-Out[5]:+Out[4]:
 dict dict
 </code> </code>
  
convert_a_string_to_a_dictionary.1677381022.txt.gz · Last modified: 2023/02/26 03:10 by raju