is this pythonic?

TP Tribulations at Paralleles.invalid
Wed Jan 21 12:34:46 EST 2009


alex23 wrote:

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

Ooooops... Moreover I know it...

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

Ok, I will use this solution. But it is less pythonic than list
comprehensions.

> Or you could just use a list comprehension:
> 
>     l = [d for d in l if d['title'] == 'ti']

Perhaps you mean rather:

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

In fact, I cannot use this solution, because I want to get back the
dictionary with title 'ti', for another use (in fact, to add it to another
list, see below).

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

In fact, in my case, in cannot use this simple solution, because there are
other fields in each dictionary, not only 2. I was not clear in my post.
So my list is rather:
l=[{"title":"to", "color":"blue", "value":2}
{"title":"ti", "color":"red", "value":"coucou"}]

So, I will rather use your solution:

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

> It's always better to design for what you know you need, not what you
> may possibly need in the future.

Ok. Do all the programmers agree with this principle?

-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)



More information about the Python-list mailing list