通过以某个字符串开头的键来分类字典 [英] Slicing a dictionary by keys that start with a certain string
本文介绍了通过以某个字符串开头的键来分类字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这很简单,但我会喜欢一个漂亮的,幽默的方法。基本上,给定一个字典,返回仅包含以某个字符串开头的那些键的子字典。
This is pretty simple but I'd love a pretty, pythonic way of doing it. Basically, given a dictionary, return the subdictionary that contains only those keys that start with a certain string.
» d = {'Apple': 1, 'Banana': 9, 'Carrot': 6, 'Baboon': 3, 'Duck': 8, 'Baby': 2}
» print slice(d, 'Ba')
{'Banana': 9, 'Baby': 2, 'Baboon': 3}
这是一个非常简单的功能:
This is fairly simple to do with a function:
def slice(sourcedict, string):
newdict = {}
for key in sourcedict.keys():
if key.startswith(string):
newdict[key] = sourcedict[key]
return newdict
但是,确实有一个更好,更聪明,更可读的解决方案?一个发电机可以在这里帮忙吗? (我从来没有足够的机会使用它们)。
But surely there is a nicer, cleverer, more readable solution? Could a generator help here? (I never have enough opportunities to use those).
推荐答案
如何做:
在python 2.x中:
in python 2.x :
def slicedict(d, s):
return {k:v for k,v in d.iteritems() if k.startswith(s)}
在python 3.x中:
In python 3.x :
def slicedict(d, s):
return {k:v for k,v in d.items() if k.startswith(s)}
这篇关于通过以某个字符串开头的键来分类字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文