Python implements a method for converting string types to dictionary types

  • 2020-04-02 13:54:07
  • OfStack

This article briefly introduces the method of converting the string type and dictionary type in Python as an example, which is a practical function. Specific methods are as follows:

Dict to a string

We can easily convert the dict type to the string type.

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


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

Ii. String to dict

How do you turn a string into a dict?

It's as simple as eval() or exec().


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

Interested friends can debug and run this example to deepen their understanding of the program code.


Related articles: