dictionary of list from a file

Thomas Jollans nospam at jollans.com
Wed Oct 4 09:36:54 EDT 2006


On Wed, 04 Oct 2006 06:09:21 -0700, andrea.spitaleri at gmail.com let this
slip:

> b={}
> a=[]
> for line in fl.readlines():
>          info=lines.split()
>          b[info[0]] = a.append(info[1])
append does not return a value. you'll want something like
  d = {}
  for line in fl:
    key, value = line.strip().split()
    if key not in d: d[key] = []
    d[key].append(value)

or something with setdefault, as limodou suggested.
 
> for i in b:
>      print i,b[i]
you can also use:
  for k,v in d.iteritems():
    print k,v

if you're dealing with integers only, you'll want to convert the data when
reading using int() and long().

> i get
> 2 None
> 7 None
> 
> data file is:
> 2 1
> 2 2
> 2 3
> 2 4
> 7 7
> 7 8
> 7 9
> 7 10

-- 
Thomas Jollans alias free-zombie



More information about the Python-list mailing list