Re: Idiomatic Python to convert list to dict

2008-07-10 Thread craig75
On Jul 10, 10:06 am, James Fassett <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> Simple question really on a best practice. I want to avoid adding
> duplicates to a list.
>
> my_list = ['a', 'b', 'c', 'd', 'e']
> dup_map = {}
> for item in my_list:
>     dup_map[item] = True
>
> # ... sometime later
>
> for complex_dict in large_list:
>     if complex_dict["char"] not in dup_map:
>         my_list.append(complex_dict["char"])
>         dup_map[complex_dict["char"]] = True
>
> For the first part (generating the duplicate map) is there a more
> idiomatic Python method for flipping the list into a dict?
>
> Is there a better way to achieve the overall objective (as hinted at
> by the above algorithm)?
>
> Thanks in advance for any tips.
>
> James.

The dictionary seems like overkill here because, if I understand
correctly, the only value associated with a key is "True". So in that
case just remove all the code related to the dictionary (and
complex_dict) and you end up with

my_list = ['a', 'b', 'c', 'd', 'e']

# ... sometime later
for char in large_list:
if char not in my_list:
my_list.append(char)


However, as Diez suggests, use a set:

my_list = set(['a', 'b', 'c', 'd', 'e'])
# ... sometime later
for char in large_list:
my_list.add(char)   # will not add duplicates
--
http://mail.python.org/mailman/listinfo/python-list


Re: Moving to functional programming

2008-07-11 Thread craig75
On Jul 11, 3:36 am, [EMAIL PROTECTED] wrote:
> James Fassett:
>
> > # the first Pythonic attempt using comprehensions
> > result_list = [x[0] for x in tuple_list]
>
> > # the final functional way
> > [result_list, _] = zip(*tuple_list)
>
> > I really like how Python allows me to do what I feel is the most
> > natural solution (for a seasoned procedural programmer) while allowing
> > a satisfying path towards a more functional approach.
>
> The list comprehension is quite more readable to me, so I suggest you
> to use it. It's probably the default way to do it in Python.
>
> If you want functional code this is another way (I have not tested the
> relative performance but it may be quick):
>
> >>> tuple_list = (
>
> ...     ('John', 'Doe'),
> ...     ('Mark', 'Mason'),
> ...     ('Jeff', 'Stevens'),
> ...     ('Bat', 'Man')
> ...   )>>> from operator import itemgetter
> >>> map(itemgetter(0), tuple_list)
>
> ['John', 'Mark', 'Jeff', 'Bat']
>
> Bye,
> bearophile


Functional programmers love pattern matching (which I think makes the
code much easier to understand):

[x for (x,y) in tuple_list]

or

map(lambda (x,y):x, tuple_list)

--
http://mail.python.org/mailman/listinfo/python-list