List of dict in Python
I've got a list of dict in Python:
dico_cfg = {'name': entry_name, 'ip': entry_ip, 'vendor': combo_vendor, 'stream': combo_stream}
self.list_cfg.append(dico_cfg)
I append to my list a lot of dict in the same way.
Now I would like to delete one dict and only one dict in this list? What is the best way to proceed?
I've try with the index of the list, but when I remove a dict from the list, the index is modify, so after some random remove my index doesn't correspond anymore to the dict I want to remove in my list. I hope that is clear. Maybe 开发者_如何转开发I can add an "id" row in my dict, so I can ask to remove more preciously the dict I want. I'll ask to remove the dict where id is equal to the id's dict I want to remove. How can I do that?
I hope I'm enough clear. Sorry but I'm a newbie in Python.
A better solution would be to have a dict of dicts instead, indexed by the id attribute. This way, even if you remove a single dict, the other id's still remain the same.
If you have a reference to the dictionary you want to remove, you can try:
self.list_cfg.remove( your_dictionary )
If you don't have any reference to it, you'll have to try to find it first:
for d in self.list_cfg:
if d['name']=='Some name': # or some other check to identify your dict
self.list_cfg.remove(d)
break
If I get you correctly, you don't want the indices to change when you remove an element from your list
of dict
s. One solution is to use a dict
of dict
s instead.
dictOne = {'foo':'bar'}
dictTwo = {'bar':'foo'}
dictOfDicts = {0:dictOne, 1:dictTwo} #and so on
#now, del(dict[1]) will remove your element without affecting the indices of the other ones.
Identifying the dictionaries with an extra entry, as you suggest, is one viable idea:
dico_cfg = {'name': entry_name, 'ip': entry_ip, 'vendor': combo_vendor,
'stream': combo_stream, 'id': 'dico_cfg'}
self.list_cfg.append(dico_cfg)
and later
self.list_cfg[:] = [d for d in self.list_cfg if d.get('id') != 'dico_cfg']
Note that I'm assigning to the full list slice (the [:]
syntax), not to the list name -- the latter may give the impression of working sometimes, but it doesn't modify the list object (just rebinds a name), so if there are other references to the list object they won't be modified. Anyway, assigning to the name (instead of to the [:]
) has no advantage unless you want to keep the original object unmodified through other references.
If you have a reference to a dict, d
in the list, you can remove it directly without needing to use an index:
list.remove(d)
精彩评论