从字典返回前N个key:value对 [英] Return first N key:value pairs from dict

查看:131
本文介绍了从字典返回前N个key:value对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下字典d:

d = {'a': 3, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

我想返回d中的前N个key:value对(在这种情况下,N <= 4)。最有效的方法是什么?

I want to return the first N key:value pairs from d (N <= 4 in this case). What is the most efficient method of doing this?

推荐答案

前n个键没有这种用法,因为 dict 不记得首先插入了哪些键。

There's no such thing a the "first n" keys because a dict doesn't remember which keys were inserted first.

您可以获得 any n键值对:

You can get any n key-value pairs though:

n_items = take(n, d.iteritems())

这使用来自take 的实现docs.python.org/library/itertools.html#recipes rel = noreferrer> itertools 食谱:

This uses the implementation of take from the itertools recipes:

from itertools import islice

def take(n, iterable):
    "Return first n items of the iterable as a list"
    return list(islice(iterable, n))

查看在线工作: ideone



更新对于Python 3.6

n_items = take(n, d.items())

这篇关于从字典返回前N个key:value对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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