简体   繁体   中英

Print a dictionary in python

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

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))

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.

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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM