0

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
Albert
  • 113
  • 2
  • 12
  • I think you are looking for this question - http://stackoverflow.com/questions/20585920/how-to-add-multiple-values-to-a-dictionary-key-in-python. A key that has multiple values. – LittlePanda Apr 27 '15 at 06:05
  • why dont you use pprint & if possible could you post the expected output, so tat it will be easy to understand the problem you are trying to solve – Ram Apr 27 '15 at 06:42

3 Answers3

1

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))
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
0

Loop over the dicts .items() and use string formatting and str#join to make the name.

.join takes an iterable (list of strings in your example) and concatenates them onto the empty string from which you call join on.

for id, name in d.items():
   print "{0} {1}".format(id, ' '.join(name))

should yield what you're looking for.

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
0

You can use str.join to concatenate lists into a single string.

You can also use str.format to make it easier to build strings:

Both of these functions should also be available in Python 2.x unless you're using a very old version.

You also have an issue with how you build your dictionary, dict.fromkeys sets all values to the same value (the one you provide). You should use dict(zip(ids, names)) instead.

And finally, the way you're using sorted is wrong since sorted returns a sorted copy. In this case you'll end up with a sorted copy of the keys in the dictionary that is immediately thrown away. Use sort together with .items() when iterating instead:

d=dict(zip(ids, names))
for id, name in sorted(d.items(), key=lambda i: int(i[0])):
    print("ID:{}, name: {}".format(id, " ".join(name)))
Raniz
  • 10,882
  • 1
  • 32
  • 64