我有一個串列:-
[['Grade', 'V A'], ['Attendance', '16/26'], ['會話時間', '8: 00 am - 8: 40 am'], ['成績', 'VII A'], ['出席', '24/31'], ['會話時間', '8: 50 am - 9: 30 am'], ['Grade', 'IX A'], ['Attendance', '20/26'], ['會話時間', '9: 40 am - 10: 20 am'], ['成績', 'IX B'], ['出席', '21/25'], ['會話時間', '10: 50 am - 11:30 am']] 。
并且想把它轉換為字典,就像這樣:-
{{"Grade"/span>:"V A"/span>}, {"Attendance"/span>: "16/26"}。... }
我試著用zip方法:-
keys = []
值 = []
for i in range(0, 12)。
string = str(message_list[i]).replace(',','; '). replace('['/span>,''). replace(']','').replace("'","") .split(" ;")
keys.append(string[0])
values.append(string[1] )
new_dict = dict(zip(keys, values))
print(new_dict)
但它只列印:-
{'grade': ' IX B', ' Attendance': ' 21/25', '會話時間': ' 10:50 am - 11:30 am'}。
它只列印了九年級B班,沒有列印其他三個年級。請幫助我解決這個問題。
但是當我使用new_dict = list(zip(keys, values))時,它把整個列印成一個圖元的串列:
[('Grade', ' V A'), ('Attendance', ' 16/26'), ('會話時間', ' 8: 00 am - 8: 40 am'), ('Grade', ' VII A'), (' Attendance', ' 24/31'), ('會話時間', ' 8: 50 am - 9: 30 am'),('Grade', ' IX A'),('Attendance'。' 20/26'), ('會話時間', ' 9: 40 am - 10: 20 am'),('Grade', ' IX B'),('Attendance'。' 21/25'), ('會話時間', ' 10: 50 am - 11:30 am')] 。]
那為什么不列印完整的字典?請用代碼幫助我。
謝謝你!
uj5u.com熱心網友回復:
你不能讓同一個鍵(例如,'Grade')在字典中重復多次......。鍵必須是唯一的。
你可以這樣做:
from collections import defaultdict
d = defaultdict(list)
for k, v in lst:
d[k].append(v)
d = dict(d)
結果是:
{'Grade': ['V A'/span>, 'VII A'/span>, 'IX A'/span>, 'IX B'/span>]。
'Attendance': ['16/26', '24/31', '20/26', '21/25'] 。
'會話時間': ['8:00 am - 8:40 am', '8: 50 am - 9:30 am', '9:40 am - 10:20 am', '10:50 am - 11:30 am']}。
uj5u.com熱心網友回復:
原因是你正在覆寫已經存在的鍵,因此在你的dict中只能看到list的最后一個條目。另一種方法是有一個嵌套的dict,如下:
{
'Grade-V A': {
'Attendance': '16/26',
'Session timings': '8:00 am - 8:40 am'.
},
'Grade-VII A': {
'Attendance': '24/31',
'Session timings': '8:50 am - 9:30 am'.
},
'Grade-IX A': {
'Attendance': '20/26',
'Session timings': '9:40 am - 10:20 am'.
},
'Grade-IX B': {
'Attendance': '21/25',
'Session timings': '10:50 am - 11:30 am'.
}
}
用下面的代碼:
data = [['Grade', 'V A'], ['Attendance', '16/26'], ['會話時間', '8: 00 am - 8: 40 am'], ['成績', 'VII A'], ['出席', '24/31'], ['會話時間', '8: 50 am - 9: 30 am'], ['Grade', 'IX A'], ['Attendance', '20/26'], ['會話時間', '9: 40 am - 10: 20 am'], ['成績', 'IX B'], ['出席', '21/25'], ['會話時間', '10: 50 am - 11:30 am']]
輸出={}。
for item in data:
if item[0] == 'grade':
grade = item[0] '-'/span> item[1]
output[grade] = {}。
else:
output[grade][item[0] ] = item[1]
print (output)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/308563.html
標籤:
