[Tutor] List to dictionary question

Mike Hansen Mike.Hansen at atmel.com
Wed Dec 6 17:39:07 CET 2006


 

> -----Original Message-----
> From: tutor-bounces at python.org 
> [mailto:tutor-bounces at python.org] On Behalf Of Morpheus
> Sent: Wednesday, December 06, 2006 9:00 AM
> To: tutor at python.org
> Subject: [Tutor] List to dictionary question
> 
> I'm new to programming, and trying to learn the Python language.  
> The following code does what I want it to do, but I have not 
> idea how it
> works.  
> 
> def scanList(names,temp):
>     for i in names:
>         temp[i] = 0
>     print temp
> 
> Names = []
> temp = {}
> 
> I have a list of names (Names[]) and want to remove duplicate names in
> the list.  Here is what I think is happening (please correct me if I'm
> wrong, or using the wrong technical terminology):  I'm passing the
> variables Names and temp as arguments to the scanList function.  The
> statement (for i in names:) is an iteration going through each item in
> the list.  The next statement (temp[i] = 0) is where I get confused.
> Can someone please explain what is happening here.  
>     
> Thanks for your help.
> 

temp is a dictionary. Dictionaries have unique keys. scanList goes
through each item in names and sets the key of the temp dictionary to
the item. If there are more than one item of the same value, it just
sets the key of the dictionary again. The statement temp[i] = 0 is
setting the value of the key 'i' to 0. (temp[key] = value) To get your
list without duplicates just get the keys of the dictionary after the
list has been run through function.
temp.keys()

If you have names = [1,2,3,2,4]
The temp dictionaries keys become 1,2,3,4.
In the scanList function above
temp[1] = 0
temp[2] = 0
temp[3] = 0
temp[2] = 0 <- It's just setting the same key to zero again.
temp[4] = 0

temp.keys() 
[1,2,3,4]

I hope that makes some sense. 

I think a more explicit way of removing duplicates from a list is using
sets.

In [1]: x = ['a', 'a', 'b', 'c', 'd', 'e', 'f', 'f', 'f']

In [2]: se = set(x)

In [3]: se
Out[3]: set(['a', 'c', 'b', 'e', 'd', 'f'])

In [4]: sel = list(se)

In [5]: sel
Out[5]: ['a', 'c', 'b', 'e', 'd', 'f']
-------------- next part --------------
-------------

  NOTICE:  This e-mail transmission and any documents or files attached to
  it contain information for the sole use of the above-identified individual or entity.

  Its contents may be privileged, confidential, and exempt from disclosure under the law.
  Any dissemination, distribution, or copying of this communication is strictly prohibited.

  Please notify the sender immediately if you are not the intended recipient.

FGNS


More information about the Tutor mailing list