3

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

 1 year ago
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.
neoserver,ios ssh client

Python中字典转换成字符串的3种方法 - 迷途小书童的Note迷途小书童的Note

> 编程语言 > Python > Python基础 > Python中字典转换成字符串的3种方法
  • windows 11 64bit
  • python 3.10.9

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

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



  1. dictionary = {"a": "A", "b": "B", "c": "C"}
  2. print("Dictionary: ", dictionary)
  3. converted = str()
  4. for key in dictionary:
  5. converted += key + ": " + dictionary[key] + ", "
  6. print("The obtained string: " + converted + " type: ", type(converted))

程序的输出



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

使用内置 str 方法



  1. dictionary = {1: "A", 2: "B", 3: "C"}
  2. print("Dictionary: ", dictionary, " type: ", type(dictionary))
  3. string = str(dictionary)
  4. print("Dict into stringa: " + string + " type ", type(string))

程序的输出



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

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



  1. from json import dumps
  2. dictionary = {"book": "The Invisible Man", "class": 12, "grade": "A"}
  3. print("Dictionary: ", dictionary)
  4. converted = dumps(dictionary)
  5. print("Dict to string: " + converted + " type: ", type(converted))


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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK