Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a python dict to a string and back

I am writing a program that stores data in a dictionary object, but this data needs to be saved at some point during the program execution and loaded back into the dictionary object when the program is run again. How would I convert a dictionary object into a string that can be written to a file and loaded back into a dictionary object? This will hopefully support dictionaries containing dictionaries.

like image 220
AJ00200 Avatar asked Dec 28 '10 15:12

AJ00200


People also ask

Can I convert a dictionary to string Python?

To convert a dictionary to string in Python, use the json. dumps() function. The json. dumps() is a built-in function in json library that can be used by importing the json module into the head of the program.

Can I reverse dictionary Python?

Instead of using a for loop, we can reverse a dictionary in a single python statement using dictionary comprehension. Here, we will create the output dictionary by reversing the key and value in each key-value pair of the dictionary as follows.

Should I use dict () or {}?

With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.


1 Answers

The json module is a good solution here. It has the advantages over pickle that it only produces plain text output, and is cross-platform and cross-version.

import json json.dumps(dict) 
like image 65
Tyler Eaves Avatar answered Sep 18 '22 09:09

Tyler Eaves