Print a dictionary in python
Question: I have a file that looks like this:

    
    
    5 John Doe 
    3 Jadzia Kowalska
    13 Heather Graham
    44 Jane Doe
    

I read it in, split it up and save it up in a dictionary with the number as
the key and a list as the value and each word as a separate string in the
list. I want to print each id followed by its name out to the command line but
I am unsure how to do so since each name is a list of strings. Would I need a
triple for loop? Any help would be greatly appreciated!

    
    
    import sys
    
    
    filename=sys.argv[1]
    
    #reads file into list
    with open(filename) as f:
       filecontent = f.readlines()
    
    names=[]
    ids=[]
    
    for i in filecontent:
        split=i.split()
        names.append(split[1:])
        ids.append(split[0])
    
    
    d= dict.fromkeys(ids,names)
    sorted(d, key=d.get)
    
    for id, name in d:
      print id, name
    


Answer: Use:

    
    
    for id, name in d:
      print id, ' '.join(name)
    

The way this works is that

    
    
    ' '.join(['first', 'last'])
    

Joins all elements in the list with an empty space as its separator. This
would also work if you wanted to create a `CSV` file in which case you would
use a comma as the separator. For example:

    
    
    ','.join(['first', 'second', 'third']) 
    

If you want to print with a space between ID and the name, use

    
    
    print "{0} {1}".format(id, ' '.join(name))
    

