Python Dictionary - How to convert String dictionary to dictionary object
Published August 09, 2021In this python example we are going to convert string object dictionary to dictionary object. To convert string to dictionary we are going to use below two ways
-
json.loads
-
ast.literal_eval
Now let's check how to use these two ways to convert dictionary
With json.loads:
loads() is a default method of JSON package will convert valid dictionary string to diction object
import json stringA = '{"languages":["Python","Docker","Java","Flutter"]}' # Given string dictionary print("Given string : \n",stringA) # using json.loads() res = json.loads(stringA) # Result print("The converted dictionary : \n",res) |
Output:
This will print below output
Given string : {"languages":["Python","Docker","Java","Flutter"]} The converted dictionary : {'languages': ['Python', 'Docker', 'Java', 'Flutter']} |
Parse dictionary object
Now if we want to print the languages from the given diction we will print by passing the languages key word.
print("Fetch languages from Dictionary: \n",res['languages']) |
This will print below output
Fetch languages from Dictionary : ['Python', 'Docker', 'Java', 'Flutter'] |
To print a specific language we need to pass the index of the
lng = res['languages'] for k in lng: print(k) |
Output
Python Docker Java Flutter |
with ast.literal_eval
This method is from ast module, to use this we need to import the ast module
import ast stringA = '{"languages":["Python","Docker","Java","Flutter"]}' # Given string dictionary print("Given string : \n",stringA) res = ast.literal_eval(stringA) # Result print("The converted dictionary : \n",res) print("Fetch languages from Dictionary : \n",res['languages']) lng = res['languages'] for k in lng: print(k) |
Output:
{'languages': ['Python', 'Docker', 'Java', 'Flutter']} Fetch languages from Dictionary : ['Python', 'Docker', 'Java', 'Flutter'] Python Docker Java Flutter |
Article Contributed By :
|
|
|
|
506 Views |