以Pythonic方式根据键的约束过滤字典
给定一个字典,我想要得到一个新的字典,这个新字典是原字典的一个子集,方法是检查哪些键满足特定的条件。例如,对于一个键是字符串的字典,筛选出以某个特定子字符串开头的键。
» 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
但是,肯定还有更好、更聪明或者更“易读”的解决方案吧?使用生成器能帮上忙吗?(我总是希望能有更多机会用到它们)。
3 个回答
3
在 Python 3 中,使用 items()
方法来代替:
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()))
这段代码的意思是,从一个叫做 `sourcedict` 的字典里筛选出那些键(也就是字典里的“名字”)以某个特定的字符串开头的项,然后把这些筛选出来的项重新放进一个新的字典里。
具体来说,`filter` 是用来过滤的,`lambda` 是一种简化写法,用来定义一个小函数。这个小函数检查每个项的键是否以 `string` 开头。如果是,就把这个项保留下来。最后,`dict` 把这些保留下来的项变成一个新的字典。
80
这样怎么样:
在 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)}