📜  Python|将字典对象转换为字符串

📅  最后修改于: 2022-05-13 01:54:25.755000             🧑  作者: Mango

Python|将字典对象转换为字符串

字典是一个重要的容器,几乎用在日常编程和网络开发的每一个代码中,它用得越多,掌握它的要求就越多,因此了解它的操作是必要的。
让我们看看将字典更改为字符串的不同方法。
方法 #1:使用 json.dumps()
json.dumps() 是 json 库中的内置函数。它比 pickle 具有优势,因为它具有跨平台支持。

Python3
# Python code to demonstrate
# to convert dictionary into string
# using json.dumps()
  
import json
  
# initialising dictionary
test1 = { "testname" : "akshat",
          "test2name" : "manjeet",
          "test3name" : "nikhil"}
  
# print original dictionary
print (type(test1))
print ("initial dictionary = ", test1)
  
# convert dictionary into string
# using json.dumps()
result = json.dumps(test1)
  
# printing result as string
print ("\n", type(result))
print ("final string = ", result)


Python3
# Python code to demonstrate
# to convert dictionary into string
# using str()
  
# initialising dictionary
test1 = { "testname" : "akshat",
          "test2name" : "manjeet",
          "test3name" : "nikhil"}
  
# print original dictionary
print (type(test1))
print ("initial dictionary = ", test1)
  
# convert dictionary into string
# using str
result = str(test1)
  
# print resulting string
print ("\n", type(result))
print ("final string = ", result)



输出:
initial dictionary = {‘testname’: ‘akshat’, ‘test2name’: ‘manjeet’, ‘test3name’: ‘nikhil’}
 
final string = {“testname”: “akshat”, “test2name”: “manjeet”, “test3name”: “nikhil”} 


方法 #2:使用 str()
str()函数将指定的值转换为字符串。

Python3

# Python code to demonstrate
# to convert dictionary into string
# using str()
  
# initialising dictionary
test1 = { "testname" : "akshat",
          "test2name" : "manjeet",
          "test3name" : "nikhil"}
  
# print original dictionary
print (type(test1))
print ("initial dictionary = ", test1)
  
# convert dictionary into string
# using str
result = str(test1)
  
# print resulting string
print ("\n", type(result))
print ("final string = ", result)


输出:
initial dictionary = {‘test2name’: ‘manjeet’, ‘testname’: ‘akshat’, ‘test3name’: ‘nikhil’}
 
final string = {‘test2name’: ‘manjeet’, ‘testname’: ‘akshat’, ‘test3name’: ‘nikhil’}