在Python

时间:2016-10-10 19:03:09

标签: json python-3.x dictionary

我有一个带有一堆键值对的XML,它们具有相同的键名。我想将它们作为JASON保存到PGSQL DB。据我所知,我可以将这些对存储在Python字典变量中,同时我会浏览XML并收集整个列表。问题是我无法将它们添加到字典中,因为它们具有相同的键名并覆盖前一个元素。例如,我有一个该结构的字典:

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

如何添加具有以下结构的其他记录:

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

我如何访问它们?删除?

1 个答案:

答案 0 :(得分: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])