Python中字典转换成字符串的3种方法
source link: https://xugaoxiang.com/2023/07/17/3-methods-convert-dict-to-string-in-python/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Python中字典转换成字符串的3种方法 - 迷途小书童的Note迷途小书童的Note
- 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'>
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK