is this pythonic?

Peter Otten __peter__ at web.de
Thu Jan 22 04:34:51 EST 2009


TP wrote:

> Hi,
> 
> Is the following code pythonic:
> 
>>>> l=[{"title":"to", "value":2},{"title":"ti","value":"coucou"}]
>>>> dict = [ dict for dict in l if dict['title']=='ti']
>>>> l.remove(*dict)
>>>> l
> [{'title': 'to', 'value': 2}]
> 
> Precision: I have stored data in the list of dictionaries l, because in my
> application I am sure that "title" is unique for each record. But perhaps
> it is better to imagine that someday it will not be anymore the case? And
> rather use a data storage as the following?
> 
> l = { '001':{"title":"to", "value":2}, '002'
> {"title":"ti","value":"coucou"}}
> 
> The problem with this storage is that it implies to manipulate some "ids"
> that have not any meaning for a humain being (001, 002, etc).
> 
> Thanks a lot for you opinion,

If you can change the rest of your program to work smoothly with a
dictionary I would suggest the following:

>>> items = [{"title":"to", "value":2},{"title":"ti","value":"coucou"}]
>>> lookup = dict((item["title"], item) for item in items)
>>> lookup
{'to': {'value': 2, 'title': 'to'}, 'ti':
{'value': 'coucou', 'title': 'ti'}}
>>> del lookup["ti"]
>>> lookup
{'to': {'value': 2, 'title': 'to'}}

If you later have to accomodate for multiple dictionaries with the same
title use lists of dictionaries as values:

>> from collections import defaultdict
>>> lookup = defaultdict(list)
>>> for item in items:
...     lookup[item["title"]].append(item)
...
>>> lookup
defaultdict(<type 'list'>, {'to': [{'value': 2, 'title': 'to'}], 'ti':
[{'value': 'coucou', 'title': 'ti'}]})
>>> del lookup["ti"] 
>>> lookup
defaultdict(<type 'list'>, {'to': [{'value': 2, 'title': 'to'}]})

Peter



More information about the Python-list mailing list