python dict多个重复键文件

2024-09-24 22:17:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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

如何处理这种输出并获得上述输出。你知道吗

注:我不坚持口述任何其他方法或解决方案将是好的,只要它产生预期的结果


Tags: 代码inforiflinekillstripdead
3条回答

你可以试试这个:

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'}}

看来你需要把容器再深一层。下面是您的代码,并做了一些调整:

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

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

相关问题 更多 >