我对Python还不熟悉。我有下面的测试文件。相同的键在testfile中重复。你知道吗
下面是testfile输出:
Police Station1
kill: 10
dead: 20
Encounter: 5
Police Station2
kill: 15
dead: 20
Encounter: 6
Police Station3
kill: 20
dead: 15
Encounter: 10
如何使用python dict获取死亡细节。我使用了下面的代码。它只打印警察局3的详细资料,不打印警察局1和2。你知道吗
代码如下:
d = {}
with open('testfile.txt') as f:
for line in f:
if ":" not in line:
continue
key, value = line.strip().split(":", 1)
d[key] = value
for k, v in d.iteritems():
if k == 'dead':
v = v.strip()
print v
if k == 'kill':
v = v.strip()
print v
我得到以下输出:
15
20
我期待着:
Police Station1
kill: 10
dead: 20
Police Station2
kill: 15
dead: 20
Police Station3
kill: 20
dead: 15
如何处理这种输出并获得上述输出。你知道吗
注:我不坚持口述任何其他方法或解决方案将是好的,只要它产生预期的结果
你可以试试这个:
看来你需要把容器再深一层。下面是您的代码,并做了一些调整:
如果你想从字典中找到一个特定的条目,你不必迭代整个条目来寻找它,你可以直接查找它,如上面的例子
dsub['dead']
。你知道吗请注意,在字典迭代中,项以任意顺序出现。如果这是一个问题,你可以使用
sorted(d.iteritems())
或者你可以说from collections import OrderedDict
并用它来代替普通的dict
输出:
警察局1
杀戮:10
死亡人数:20
警察局3
杀戮:20
死亡人数:15
警察局2
杀戮:15
死亡人数:20
相关问题 更多 >
编程相关推荐