Appending to dictionary of lists

Discussion in 'Python' started by Alex van der Spek, May 3, 2011.

  1. I open a csv file and create a DictReader object. Subsequently, reading
    lines from this file I try to update a dictionary of lists:

    csvf=open(os.path.join(root,fcsv),'rb')
    csvr=csv.DictReader(csvf)
    refd=dict.fromkeys(csvr.fieldnames,[])
    for row in csvr:
    for (k,v) in row.items():
    refd[k].append(v)

    I do not understand why this appends v to every key k each time.

    Thanks in advance for any tips you can pass on.

    Alex van der Spek
     
    Alex van der Spek, May 3, 2011
    #1
    1. Advertising

  2. Alex van der Spek

    Paul Rubin Guest

    "Alex van der Spek" <> writes:
    > refd=dict.fromkeys(csvr.fieldnames,[]) ...
    > I do not understand why this appends v to every key k each time.


    You have initialized every element of refd to the same list. Try

    refd = dict((k,[]) for k in csvr.fieldnames)

    instead.
     
    Paul Rubin, May 3, 2011
    #2
    1. Advertising

  3. Thank you! Would never have found that by myself.


    "Paul Rubin" <> wrote in message
    news:...
    > "Alex van der Spek" <> writes:
    >> refd=dict.fromkeys(csvr.fieldnames,[]) ...
    >> I do not understand why this appends v to every key k each time.

    >
    > You have initialized every element of refd to the same list. Try
    >
    > refd = dict((k,[]) for k in csvr.fieldnames)
    >
    > instead.
     
    Alex van der Spek, May 3, 2011
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ilias Lazaridis
    Replies:
    6
    Views:
    444
    Ilias Lazaridis
    Feb 21, 2006
  2. =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==

    List of lists of lists of lists...

    =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==, May 8, 2006, in forum: Python
    Replies:
    5
    Views:
    410
    =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==
    May 15, 2006
  3. Replies:
    2
    Views:
    227
  4. james_027
    Replies:
    1
    Views:
    329
    Marc 'BlackJack' Rintsch
    Aug 22, 2007
  5. Navkirat Singh
    Replies:
    6
    Views:
    3,074
    Navkirat Singh
    Jul 29, 2010
Loading...

Share This Page