从字典中删除某个索引的项目? [英] Removing items of a certain index from a dictionary?

查看:103
本文介绍了从字典中删除某个索引的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个字典并且已对其进行了排序,并且我想按索引从索引中删除前三个项(按值的顺序)(无论初始字典的内容是什么),我该怎么办?我将如何去做? 我希望它可以让我切片(例如使用列表),但是我已经意识到这是不可能的.

If I've got a dictionary and it's sorted, and I want to remove the first three items (in order of value) from it by index (no matter what the contents of the initial dictionary was), what do I do? How would I go about doing so? I was hoping it would let me just slice (such as one does with lists), but I've been made aware that that's impossible.

按索引,我指的是索引.因此,举例来说,如果我从下面的排序字典中删除了1到3个项目,然后按值对它进行排序,那么我只会留下鸡蛋". 那我如何在那些地方找到索引(索引0、1、2)? 我不允许在其中导入或打印.

By index I mean indices. So for example, were I to remove the items from 1 to 3 of the sorted dictionary below, after it was sorted by value, then I would only be left with "eggs". EDIT 2: How do I find the keys in those places then (in indices 0, 1, 2)? EDIT 3: I'm not allowed to import or print in this.

例如:

>>>food = {"ham":12, "cookie":5, "eggs":16, "steak":2}
>>>remove_3(food)
{"eggs":16}

推荐答案

获取键值对(.items()),按值(item[1])对它们进行排序,并获取前3个([:3]):

Get key value pairs (.items()), sort them by value (item[1]), and take the first 3 ([:3]):

for key, value in sorted(food.items(), key=lambda item: item[1])[:3]:
    del food[key]

这篇关于从字典中删除某个索引的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆