Idiomatic Python to convert list to dict
Diez B. Roggisch
deets at nospam.web.de
Thu Jul 10 13:13:46 EDT 2008
James Fassett schrieb:
> 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.
Instead of a dict, use a set. It's immediatly contructable from my_list,
and better suited for the task anyway.
Diez
More information about the Python-list
mailing list