Python 通过以特定字符串开头的键对字典进行切片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4558983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:18:44  来源:igfitidea点击:

Slicing a dictionary by keys that start with a certain string

pythondictionaryironpythonslice

提问by Aphex

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.

这很简单,但我喜欢一种漂亮的、pythonic 的方式。基本上,给定一个字典,返回仅包含以某个字符串开头的那些键的子字典。

? 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).

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

采纳答案by Mark Byers

How about this:

这个怎么样:

in python 2.x :

在 python 2.x 中:

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

In python 3.x :

在 python 3.x 中:

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

回答by seriyPS

In functional style:

功能风格:

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

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

回答by gc5

In Python 3use items()instead:

Python 3 中使用items()

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