如何从 python 字典中删除 key: pairs over a certain number?

给定一个数字和一个字典,“remove_numbers_larger_than”删除任何值大于给定数字的键。返回修改后的字典。


def remove_numbers_larger_than(dictionary, number):

    for k, v in dictionary.items():

        if v > number:

            del d[k]

    return dictionary


PIPIONE
浏览 149回答 3
3回答

慕桂英3389331

如果您需要dict就地修改给定,请先复制键,以便从字典中删除键不会干扰迭代。def remove_numbers_larger_than(dictionary, number):&nbsp; &nbsp; keys = list(dictionary)&nbsp; &nbsp; for k in keys:&nbsp; &nbsp; &nbsp; &nbsp; if dictionary[k] > number:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; del dictionary[k]&nbsp; &nbsp; return dictionary如果您有空创建一个新的dict,def remove_numbers_larger_than(dictionary, number):&nbsp; &nbsp; return dict(kv for kv in dictionary.items() if kv[1] <= number)

翻阅古今

就地方法可以稍微简化一下。整个字典只迭代一次,辅助列表只包含有问题的键,而不是所有键。for&nbsp;k&nbsp;in&nbsp;[k&nbsp;for&nbsp;k,&nbsp;v&nbsp;in&nbsp;dictionary.items()&nbsp;if&nbsp;v&nbsp;>&nbsp;number]: &nbsp;&nbsp;&nbsp;&nbsp;del&nbsp;dictionary[k]

慕田峪7331174

您可以使用此代码段,它将遍历字典,选择小于或等于给定数字的数字,并使用所选数字创建一个新字典。def remove_numbers_larger_than(dictionary, number):&nbsp; &nbsp; return { key: dictionary[key] for key in dictionary if dictionary[key] <= number }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python