iteritems:匹配k值下部/上和白色空间



我正在使用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  :

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

k == "items":

如果在上案中"项目"或有空间。

请帮助修复我的脚本。

重新定义k以小写并用

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

您可以使用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

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

我们可以使用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

最新更新