我是python的新手。我有下面的testfile。在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获取kill和dead details。我使用下面的代码。它只打印警察局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
如何处理这种输出并获得上述输出。
注意:我不会坚持任何其他方法或解决方案,只要它能产生预期的预期效果
答案 0 :(得分:0)
d = {}
holder = ""
with open('test.txt', 'r') as f:
for line in f:
line = line.strip()
if line != "":
if ":" not in line:
d[line] = {}
holder = line
else:
key, value = line.strip().split(":")
d[holder][key] = value
#here in the below line, you were overwriting the values each time
#so only the values that were assigned last time will remain
#In your case, {'kill': ' 20', 'Encounter': ' 10', 'dead': ' 15'}
#d[key] = value
for k in d:
print k
for item in d[k]:
if item != "Encounter":
print item+" : "+d[k][item]
<强>输出:强>
警察局1
杀人:10
死了:20
警察局3
杀人:20
死了:15
警察局2
杀人:15
死了:20
答案 1 :(得分:0)
你可以试试这个:
f = open('file.txt').read().splitlines()
f = [i.split() for i in f]
f = [i for i in f if len(i) > 0]
results = {''.join(f[i:i+4][0]):{f[i:i+4][b][0]:f[i:i+4][b][1] for b in range(1, 3)} for i in range(0, len(f), 4)}
print results
#gives you: {'PoliceStation1': {'dead:': '20', 'kill:': '10'}, 'PoliceStation2': {'dead:': '20', 'kill:': '15'}, 'PoliceStation3': {'dead:': '15', 'kill:': '20'}}
答案 2 :(得分:0)
看起来你需要将容器嵌套一层。通过一些调整,再次使用您的代码:
dsub = d = {}
with open('testfile.txt') as f:
for line in f:
line = line.strip() # strip whitespace fore & aft
if not line: # ignore blank lines
continue
if ":" in line:
key, value = line.split(":", 1)
dsub[key] = value
else: # lines without colons are no long ignored: they're the outer-level keys
dsub = d[line] = {} # create a new sub-dictionary
for station, dsub in d.iteritems():
print station, dsub['kill'], dsub['dead']
如果你想从字典中获取特定的条目,你不必遍历整个事情以期找到它 - 你可以直接查找它,如示例中所示上面dsub['dead']
。
请注意,在字典迭代中,项目以任意顺序出现。如果这是一个问题,您可以使用sorted(d.iteritems())
,也可以说from collections import OrderedDict
并使用它而不是普通的dict
。