2016-10-10 109 views
0

我有一堆帶有一組鍵值對的XML,它們具有相同的鍵名。我想將它們保存爲PGSQL DB的JASON。據我所見,我可以將這些對存儲在Python字典變量中,而我正在瀏覽XML並收集整個列表。問題是我無法將它們添加到字典中,因爲它們具有相同的鍵名稱並覆蓋了以前的元素。例如,我有一個結構的字典:在Python中填充具有相同鍵名的字典

data=[{'contactid': 'id0', 'score': 'score0'},{'contactid': 'id1', 'score': 'score1'}] 

如何,我可以添加另一條記錄與結構如下:

{'contactid': 'id2', 'score': 'score2'} 

我如何訪問它們?刪除?

+1

'data.append()'? –

+0

我不明白你的觀點。這是一個列表,爲什麼你不能在數據中附加一個新的字典? – MMF

+0

我對Python很陌生。 data.append()正在做我想要的。 –

回答

1

要添加一個新的字典到您的列表中,只需使用方法:append()

如果你想訪問你的列表中給定的字典,你是否知道它的位置,你只要做list[index]其中index是你的字典中的列表中的位置,也可以如下操作來關注一下吧使用其值:

request_list = [] # list that will contain dictionaries you are looking for 

# Say you are looking for dictionary with values : id0 and score0 
mask = [(data[i]['contactid']=='id0') & (data[i]['score']=='score0') for i in range(len(data))] 

for i, bool in enumerate(mask): 
    if bool: 
     request_list.append(data[i])