繁体   English   中英

从字典中获取 N 个项目的更 Pythonic 的方式是什么?

[英]What's a more Pythonic way of grabbing N items from a dictionary?

在 Python 中,假设我想从字典中获取 N 个任意项——比如说,打印它们,检查一些项。 我不在乎我得到了哪些物品。 我不想把字典变成一个列表(就像我看到的一些代码一样); 这似乎是一种浪费。 我可以使用以下代码(其中 N = 5)来做到这一点,但似乎必须有一种更 Pythonic 的方式:

count = 0
for item in my_dict.items():
    if count >= 5:
        break
    print(item)
    count += 1

提前致谢!

您可以使用itertools.islice对任何可迭代对象(不仅是列表)进行切片:

>>> import itertools
>>> my_dict = {i: i for i in range(10)}
>>> list(itertools.islice(my_dict.items(), 5))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

我可能会使用ziprange

>>> my_dict = {i: i for i in range(10)}
>>> for _, item in zip(range(5), my_dict.items()):
...     print(item)
...
(0, 0)
(1, 1)
(2, 2)
(3, 3)
(4, 4)

此处range的唯一目的是提供一个可迭代的对象,该可迭代对象将导致zip在 5 次迭代后停止。

您可以稍微修改一下:

for count, item in enumerate(dict.items()):
    if count >= 5:
        break
    print(item)

注意:在这种情况下,当您遍历 .items() 时,您将获得一个键/值对,可以在迭代时对其进行解包:

for count, (key, value) in enumerate(dict.items()):
    if count >= 5:
        break
    print(f"{key=} {value=})

如果你只想要键,你可以遍历字典。

for count, key in enumerate(dict):
    if count >= 5:
        break
    print(f"{key=})

如果您只想要这些值:

for count, value in enumerate(dict.values()):
    if count >= 5:
        break
    print(f"{value=})

最后一点:使用dict作为变量名会覆盖内置的dict并使其在您的代码中不可用。

通常,我想使用切片表示法来执行此操作,但dict.items()返回一个不可切片的迭代器

您有两个主要选择:

  1. 让它成为切片符号适用的东西:
x = {'a':1, 'b':2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
for item, index in list(x.items())[:5]:
  print(item)
  1. 使用适用于迭代器的东西。 在这种情况下,内置(并且非常流行)的 itertools 包:
import itertools
x = {'a':1, 'b':2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
for item in itertools.islice(x.items(), 5):
  print(item)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM