我有一个像这样的文本文件
128.220.251.50
130.79.48.57
203.110.240.191
128.220.251.50 208.94.63.193
128.36.233.154
128.36.233.154 131.246.112.29
128.36.233.154 136.145.115.196
130.79.48.57 203.110.240.191
131.246.112.29 199.26.254.68
136.145.115.196 128.220.251.50
136.145.115.196 140.247.60.123
137.165.1.113
137.165.1.113 128.220.251.50
137.165.1.113 128.36.233.154
137.165.1.113 130.79.48.57
140.247.60.123 137.165.1.113
199.26.254.68 136.145.115.196
203.110.240.191 131.246.112.29
208.94.63.193 140.247.60.123
我想把它读入字典。这是代码。
def get_key_value(line):
key, sep, value = line.strip().partition(" ")
return key, value
with open("output.txt") as fd:
d = dict(get_key_value(line) for line in fd)
for key,value in d.iteritems():
print str(key),str(value)
以下是 print 语句的输出。
128.220.251.50 208.94.63.193
130.79.48.57 203.110.240.191
203.110.240.191 131.246.112.29
131.246.112.29 199.26.254.68
199.26.254.68 136.145.115.196
136.145.115.196 140.247.60.123
128.36.233.154 136.145.115.196
140.247.60.123 137.165.1.113
208.94.63.193 140.247.60.123
137.165.1.113 130.79.48.57
我有以下问题。如果您考虑输入,则有三个键(或行)用 137.165.1.113 说明。但是打印语句只打印其中一个。并非所有键值对都保存在字典中。而且我希望忽略输入中只有一个 IP 地址的行,这是在此代码中完成的。提前致谢。