简体   繁体   English

用python打印字典

[英]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. 我想在命令行中打印每个id及其名称,但由于每个名称都是字符串列表,因此我不确定该怎么做。 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. 如果要创建CSV文件,在这种情况下也可以使用逗号作为分隔符,这也可以使用。 For example: 例如:

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

If you want to print with a space between ID and the name, use 如果要在ID和名称之间使用空格打印,请使用

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

Loop over the dicts .items() and use string formatting and str#join to make the name. 遍历字典.items()并使用字符串格式和str#join命名。

.join takes an iterable (list of strings in your example) and concatenates them onto the empty string from which you call join on. .join接受一个可迭代的(示例中的字符串列表),并将它们串联到您称为join的空字符串上。

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. 您可以使用str.join将列表连接为单个字符串。

You can also use str.format to make it easier to build strings: 您还可以使用str.format使构建字符串更容易:

Both of these functions should also be available in Python 2.x unless you're using a very old version. 除非您使用的是非常旧的版本,否则这两个函数也应在Python 2.x中可用。

You also have an issue with how you build your dictionary, dict.fromkeys sets all values to the same value (the one you provide). 字典的构建方式也存在问题, dict.fromkeys将所有值设置为相同的值(您提供的值)。 You should use dict(zip(ids, names)) instead. 您应该改用dict(zip(ids, names))

And finally, the way you're using sorted is wrong since sorted returns a sorted copy . 最后,您使用sorted的方式是错误的,因为sorted返回了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: 迭代时, .items() sort.items()结合使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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