Idiomatic Python to convert list to dict

James Fassett james at reggieband.com
Thu Jul 10 19:35:32 CEST 2008


On Jul 10, 6:13 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
> > 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
>
> Instead of a dict, use a set. It's immediatly contructable from my_list,
> and better suited for the task anyway.

Cheers,

I rewrote it similar to:

dup_map = set(['a', 'b', 'c', 'd', 'e'])

# ... sometime later

for complex_dict in large_list:
    dup_map.add(complex_dict["char"])

my_list = list(dup_map)

That is a little nicer. Thanks again,
James.



More information about the Python-list mailing list