iteritems:匹配k值lower / upper和white space

时间:2017-06-04 16:19:52

标签: python python-2.7

我在Python 2.7中使用字典。

以下是代码:

d = {}
with open('input') 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 == 'items':

在输入文件中,他们提到了一些时间" items"如下所示:

items:
Items:
ITEMS:
     Items  :

我想在我的代码中匹配以上所有内容,现在我正在使用

k == "items":

如果" items"这不起作用大写或有空格。

请帮助修复我的脚本。

2 个答案:

答案 0 :(得分:4)

将k重新定义为小写并使用

删除空格
k = k.lower().strip()

答案 1 :(得分:2)

您可以使用str.stripstr.lower方法:

d = {}
with open('test.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.lower().strip() == 'items':
        # do work with single value

如果您需要使用类似的键处理值,最好在list对象创建的步骤中将它们收集到d

我们可以使用dict.setdefault方法

执行此操作
d = {}
with open('test.txt') as f:
    for line in f:
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        key = key.lower().strip()
        d.setdefault(key, []).append(value)

values = d['items']  # or use `d.get('items', [])` if there may not be 'items' key
# do work with multiple values

dict分机 - defaultdict

from collections import defaultdict

d = defaultdict(list)
with open('test.txt') as f:
    for line in f:
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        key = key.lower().strip()
        d[key].append(value)

values = d['items']
# do work with multiple values