我們基於字元串和字典解決了不同的問題。在本教程中,我們將看到如何在 Python 中將字元串轉換為字典。
在此之前,讓我們快速回憶一下字元串和字典。
字元串被定義為一個字元序列,並使用單引號或雙引號來表示。
例如-
flower = 'Rose'
sub = 'Python'
name = 'James'
我們可以使用類型()檢查上述變數的數據類型。
字典在 Python 中被定義為一種數據結構,它使用花括弧中的鍵值對。
我們可以在各自鍵的幫助下訪問字典中的值。
字典的例子是-
Subj = {'subj1': 'Computer Science', 'subj2': 'Physics', 'subj3': 'Chemistry', 'subj4': 'Mathematics'}
現在讓我們列出可以將字元串轉換為字典的方法。
- 使用負載()
- 使用
literal_eval
- 使用生成器表達式
是時候詳細討論它們了-
使用 json.loads()
下面的程序展示了如何使用 json.loads()將字元串轉換為字典
#using json()
import json
#initialising the string
string_1 = '{"subj1":"Computer Science","subj2":"Physics","subj3":"Chemistry","subj4":"Mathematics"}'
print("String_1 is ",string_1)
#using json.loads()
res_dict=json.loads(string_1)
#printing converted dictionary
print("The resultant dictionary is ",res_dict)
輸出:
String_1 is {"subj1":"Computer Science","subj2":"Physics","subj3":"Chemistry","subj4":"Mathematics"}
The resultant dictionary is {'subj1': 'Computer Science', 'subj2': 'Physics', 'subj3': 'Chemistry', 'subj4': 'Mathematics'}
說明:
讓我們了解一下我們在上面的程序中做了什麼-
- 在第一步中,我們已經導入了 json 模塊。
- 之後,我們已經初始化了我們想要轉換的字元串。
- 現在我們已經簡單地在 loads()中傳遞了『string _ 1』作為參數。
- 最後,在最後一步中,我們顯示了結果字典。
使用 ast.literal_eval()
現在我們來看看 ast.literal_eval 如何幫助我們實現目標。
下面的程序說明了同樣的情況-
#convert string to dictionary
#using ast()
import ast
#initialising the string
string_1 = '{"subj1":"Computer Science","subj2":"Physics","subj3":"Chemistry","subj4":"Mathematics"}'
print("String_1 is ",string_1)
#using ast.literal_eval
res_dict=ast.literal_eval(string_1)
#printing converted dictionary
print("The resultant dictionary is ",res_dict)
輸出:
String_1 is {"subj1":"Computer Science","subj2":"Physics","subj3":"Chemistry","subj4":"Mathematics"}
The resultant dictionary is {'subj1': 'Computer Science', 'subj2': 'Physics', 'subj3': 'Chemistry', 'subj4': 'Mathematics'}
說明:
讓我們了解一下我們在上面的程序中做了什麼-
- 第一步,我們已經導入了 ast 模塊。
- 之後,我們已經初始化了我們想要轉換的字元串。
- 現在我們已經簡單地在 literaleval()中傳遞了『string 1』作為參數。
- 最後,在最後一步中,我們顯示了結果字典。
使用生成器表達式
最後,在最後一個例子中,我們將討論如何使用生成器表達式。
讓我們仔細研究給定的程序。
#convert string to dictionary
#using generator expressions
#initialising the string
string_1 = "subj1 - 10 , subj2 - 20, subj3 - 25, subj4 - 14"
print("String_1 is ",string_1)
#using strip() and split()
res_dict = dict((a.strip(), int(b.strip()))
for a, b in (element.split('-')
for element in string_1.split(', ')))
#printing converted dictionary
print("The resultant dictionary is: ", res_dict)
print(type(res_dict))
輸出:
String_1 is subj1 - 10 , subj2 - 20, subj3 - 25, subj4 - 14
The resultant dictionary is: {'subj1': 10, 'subj2': 20, 'subj3': 25, 'subj4': 14}
<class 'dict'>
是時候檢查一下這種方法的解釋了-
- 在第一步中,我們已經聲明了一個字元串,它的值與一個連字元成對,每對用逗號分隔。這些信息很重要,因為它將成為獲得所需輸出的一個很好的工具。
- 此外,我們在
for
循環中使用了 strip() 和 split() ,這樣我們就可以得到通常格式的字典。 - 最後,我們列印了我們創建的字典,並使用 type()驗證了它的類型。
結論
在本教程中,我們探索了字元串到字典的轉換方法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/239879.html