欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

Python中字典转换成字符串的3种方法

Python基础 迷途小书童 9个月前 (07-17) 799次浏览 0个评论

环境

  • windows 11 64bit
  • python 3.10.9

简介

Python 提供了多种数据类型来存储各种格式的值,包括字符串、字典、列表等。在编程时,经常会遇到将一种数据类型转换为另一种数据类型的问题。字典是一种存储和映射数据的便捷格式,它的键值格式使得映射数据更加容易。如果要将字典的数据存储在文件或数据库中,字符串是更方便的存储格式。本文中,我们将了解在 Python 中将字典转换为字符串的3种方法。

方法一

使用传统方法,即遍历字典,将键和值依次进行拼接

dictionary = {"a": "A", "b": "B", "c": "C"}
print("Dictionary: ", dictionary)
converted = str()

for key in dictionary:
    converted += key + ": " + dictionary[key] + ", "

print("The obtained string: " + converted + " type: ", type(converted))

程序的输出

Dictionary:  {'a': 'A', 'b': 'B', 'c': 'C'}
The obtained string: a: A, b: B, c: C,  type:  <class 'str'>

方法二

使用内置 str 方法

dictionary = {1: "A", 2: "B", 3: "C"}
print("Dictionary: ", dictionary, " type: ", type(dictionary))

string = str(dictionary)
print("Dict into stringa: " + string + " type ", type(string))

程序的输出

Dictionary:  {1: 'A', 2: 'B', 3: 'C'}  type:  <class 'dict'>
Dict into stringa: {1: 'A', 2: 'B', 3: 'C'} type  <class 'str'>

方法三

使用 json 库的 dumps 方法。dumps() 方法将一个 JSON 对象作为输入参数,并返回一个 JSON 字符串,使用该方法之前,需要导入 JSON库。

from json import dumps

dictionary = {"book": "The Invisible Man", "class": 12, "grade": "A"}
print("Dictionary: ", dictionary)

converted = dumps(dictionary)
print("Dict to string: " + converted + " type: ", type(converted))

程序输出

Dictionary:  {'book': 'The Invisible Man', 'class': 12, 'grade': 'A'}
Dict to string: {"book": "The Invisible Man", "class": 12, "grade": "A"} type:  <class 'str'>

参考资料

喜欢 (0)

您必须 登录 才能发表评论!