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所有,未經許可,不得轉載
你可能還喜歡