python implements the interconversion method between the dictionary of dict and the string of string

  • 2020-05-26 09:33:53
  • OfStack

This article illustrates an example of how python implements string and dict. I will share it with you for your reference as follows:

Dictionary (dict) to string (string)

We can easily convert the dictionary (dict) type to the string (string) type.

Dictionary to string conversion is achieved by traversing all the elements in dict:


for key, value in sample_dic.items():
 print "\"%s\":\"%s\"" % (key, value)

String (string) to dictionary (dict)

How do you convert a string (string) to a dictionary (dict)?

It's actually very simple, just use it eval() or exec() The function is implemented.


>>> a = "{'a': 'hi', 'b': 'there'}"
>>> b = eval(a)
>>> b
{'a': 'hi', 'b': 'there'}
>>> exec ("c=" + a)
>>> c
{'a': 'hi', 'b': 'there'}
>>>

More information about Python can be found in the following topics: summary of Python dictionary operation skills, summary of Python string operation skills, summary of Python commonly used traversal skills, tutorial of Python data structure and algorithm, summary of Python function operation skills, and classic tutorial of Python introduction and advanced skills.

I hope this article is helpful to you Python programming.


Related articles: