is this pythonic?

alex23 wuwei23 at gmail.com
Wed Jan 21 11:58:15 EST 2009


On Jan 22, 1:16 am, TP <Tribulati... at Paralleles.invalid> wrote:
> 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}]

Try not to use 'dict' or the name of any of the other built-in types
as labels.

You're stepping through an entire list just to pass another list to
l.remove to step through and remove items from...in fact, given that
list.remove deletes the -first- occurance of the item, you're asking
it to loop through -again- to find the matching element which you've -
already- detected. A better and cleaner approach would be to step
through the list -once- and remove the item when you find it:

    for index, record in enumerate(l):
        if record['title'] == 'ti':
            l.pop(index)

Or you could just use a list comprehension:

    l = [d for d in l if d['title'] == 'ti']

> 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?

It's always better to design for what you know you need, not what you
may possibly need in the future. You say that you are sure that record
titles are unique, so why not use them as the dictionary keys, with
the values as the values:

  records = {'ti': 1, 'to': 2}

This way your code can be replaced with:

  value = records.pop('ti') # if you want to know the value
  del records['ti']         # if you just want to delete the entry

It's a lot simpler to work with and extend.



More information about the Python-list mailing list