Python - 返回第一个N键:来自dict的值对 [英] Python - Return first N key:value pairs from dict

查看:741
本文介绍了Python - 返回第一个N键:来自dict的值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下字典d:

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

我想返回第一个N键:value从d(在这种情况下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.

你可以得到任何键 - 价值对:

You can get any n key-value pairs though:

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

这使用 take docs.python.org/library/itertools.html#recipes> 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 - 返回第一个N键:来自dict的值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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