按以某个字符串开头的键对字典进行切片[重复]

问题描述 投票:0回答:3

这非常简单,但我喜欢一种漂亮的、Python 式的方法。基本上,给定一个字典,返回仅包含以特定字符串开头的键的子字典。

» d = {'Apple': 1, 'Banana': 9, 'Carrot': 6, 'Baboon': 3, 'Duck': 8, 'Baby': 2}
» print slice(d, 'Ba')
{'Banana': 9, 'Baby': 2, 'Baboon': 3}

使用函数实现这一点相当简单:

def slice(sourcedict, string):
    newdict = {}
    for key in sourcedict.keys():
        if key.startswith(string):
            newdict[key] = sourcedict[key]
    return newdict

但是肯定有更好、更聪明、更易读的解决方案吗?发电机可以帮忙吗? (我从来没有足够的机会使用这些)。

python dictionary ironpython slice
3个回答
79
投票

这个怎么样:

在 python 2.x 中:

def slicedict(d, s):
    return {k:v for k,v in d.iteritems() if k.startswith(s)}

在 python 3.x 中:

def slicedict(d, s):
    return {k:v for k,v in d.items() if k.startswith(s)}

9
投票

功能风格:

dict(filter(lambda item: item[0].startswith(string),sourcedict.iteritems()))


3
投票

Python 3 中使用

items()
代替:

def slicedict(d, s):
    return {k:v for k,v in d.items() if k.startswith(s)}
© www.soinside.com 2019 - 2024. All rights reserved.