Python 字典到字符串:完整指南

Python 有许多数据结构可供使用,每个结构都会向表中添加一些内容。 通常我们需要从一种数据结构转换为另一种数据结构才能无缝传递数据。

Python Dictionary 是日常编程和 Web 开发的每个代码中使用的必需容器。 用得越多,掌握它的要求就越高; 因此,有必要了解其操作。

Python 字典到字符串

要在 Python 中将字典转换为字符串,请使用 json.dumps() 函数。 json.dumps() 是一个内置函数,可将 Python 对象转换为 json 字符串。

# app.py

import json

stranger = {"Eleven": "Millie",
            "Mike": "Finn",
            "Will": "Noah"}

# print original dictionary
print("initial dictionary = ", stranger)
print(type(stranger))

# convert dictionary into string
# using json.dumps()
op = json.dumps(stranger)

# printing result as string
print("final string = ", op)
print("\n", type(op))

输出

➜  pyt python3 app.py
initial dictionary =  {'Eleven': 'Millie', 'Mike': 'Finn', 'Will': 'Noah'}

final string =  {"Eleven": "Millie", "Mike": "Finn", "Will": "Noah"}

 
➜  pyt

首先,我们必须在上面的代码中打印原始字典及其类型。 然后,我们使用 json.dumps() 函数将字典转换为字符串,然后打印字符串及其数据类型。

使用 str() 函数的 Python dict 到字符串

Python str() 是一个将指定值转换为字符串的内置函数。

# app.py

stranger = {"Eleven": "Millie",
            "Mike": "Finn",
            "Will": "Noah"}

# print original dictionary
print("initial dictionary = ", stranger)
print(type(stranger))

# convert dictionary into string
# using str()
op = str(stranger)

# printing result as string
print("final string = ", op)
print("\n", type(op))

输出

➜  pyt python3 app.py
initial dictionary =  {'Eleven': 'Millie', 'Mike': 'Finn', 'Will': 'Noah'}

final string =  {'Eleven': 'Millie', 'Mike': 'Finn', 'Will': 'Noah'}

 
➜  pyt

首先,我们在上面的代码中打印了一个原始字典及其类型。 然后,我们使用 str() 函数将字典转换为字符串。

Python字符串到字典

要将字符串转换为 Python 中的字典,请使用 ast 模块的 literal.eval() 函数。 ast.literal_eval() 是一个 ast 库方法,它可以评估包含来自未知来源的 Python 值的字符串,而无需我们解析这些值。

import ast

stranger="{"name": "Krunal", "age": "26"}"
# print original string
print("initial string = ", stranger)
print(type(stranger))

# convert string into dictionary
# using ast.literal_eval()
op = ast.literal_eval(stranger)

# printing result as string
print("final dictionary = ", op)
print("\n", type(op))

输出

➜  pyt python3 app.py
initial string =  {"name": "Krunal", "age": "26"}

final dictionary =  {'name': 'Krunal', 'age': '26'}

 
➜  pyt

首先,我们打印原始字符串及其类型,然后使用 ast.literal_eval() 函数将字符串转换为字典,然后打印字典及其类型。

这就是本教程的内容。

相关文章

Python 字典到数组

Python dict 列出

Python dict到数据框

帖子 Python dict to string: The Complete指南 首次出现在 AppDividend 上。

资讯来源:由0x资讯编译自APPDIVIDEND,版权归作者Krunal所有,未经许可,不得转载
你可能还喜欢