[英]Adding items to a dictionary in python (nested)
我知道還有其他一些與我的問題相似的問題,但我沒有真正找到適合我的問題的問題。
我在python中有一個字典,看起來像這樣:
0 = {
awayScore = 2;
awayTeam = "Floda BoIF";
homeScore = 1;
homeTeam = "SKIF Semberija";
time = "00:00";
};
1 = {
awayScore = 2;
awayTeam = "Kode IF";
homeScore = 1;
homeTeam = "Partille IF FK ";
time = "01:00";
};
這是我建造它的方式
dictionary[i] = {"time":time, "homeTeam":homeTeam,"homeScore":homeScore, "awayTeam":awayTeam,
"awayScore":awayScore}
這是所有項目的“開始位置”,稍后我將獲得POST請求,客戶端將發送應添加到詞典中的“事件”信息。 像這樣的東西(語法可能不正確,但是您會得到我想做的事情):
{
0 = {
awayScore = 2;
awayTeam = "Floda BoIF";
events = {
0 {
eventType = Goal;
name = "Muchache Johansson";
}
1 {
eventType = Yellow Card;
name = "Muchache Johansson";
}
};
homeScore = 1;
homeTeam = "SKIF Semberija";
time = "00:00";
};
1 = {
awayScore = 2;
awayTeam = "Kode IF";
events = {
0 {
eventType = Goal;
name = "Garcia Muchache";
}
};
homeScore = 1;
homeTeam = "Partille IF FK ";
time = "01:00";
};
因此,起初他們根本沒有任何事件。 然后,如果他們沒有該事件,則可以添加一個ID為0的事件。也許同一項目出現另一個發布請求,則應添加另一個ID為1的事件,依此類推。 這有可能嗎? 謝謝您的幫助。
這非常簡單>您可以隨意注入元素
dictionary = {0 : {
'awayScore' : 2,
'awayTeam' : "Floda BoIF",
'homeScore' : 1,
'homeTeam' : "SKIF Semberija",
'time' : "00:00",
'events' : {}
},
1 : {
'awayScore' : 2,
'awayTeam' : "Kode IF",
'homeScore' : 1,
'homeTeam' : "Partille IF FK ",
'time' : "01:00",
'events' : {}
}
當事件發生時,您可以注入它:例如
dictionary[0]['events'][0] = {
'eventType' : 'Goal',
'name' : 'Muchache Johansson',
}
如果您要使用事件列表而不是字典來保留順序而不必擔心,則必須通過"events":[]
設置它"events":[]
並附加一個帶有
dictionary[0]['events']. append({
'eventType' : 'Goal',
'name' : 'Muchache Johansson',
}
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.