Home > OS >  What's a more Pythonic way of grabbing N items from a dictionary?
What's a more Pythonic way of grabbing N items from a dictionary?

Time:03-28

In Python, suppose I want to grab N arbitrary items from a dictionary—say, to print them, to inspect a few items. I don't care which items I get. I don't want to turn the dictionary into a list (as does some code I have seen); that seems like a waste. I can do it with the following code (where N = 5), but it seems like there has to be a more Pythonic way:

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

Thanks in advance!

CodePudding user response:

You can use itertools.islice to slice any iterable (not only lists):

>>> 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)]

CodePudding user response:

I might use zip and range:

>>> 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)

The only purpose of the range here is to give an iterable that will cause zip to stop after 5 iterations.

CodePudding user response:

You can modify what you have slightly:

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

Note: in this case when you're looping through .items(), you're getting a key/value pair, which can be unpacked as you iterate:

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

If you want just the keys, you can just iterate over the dict.

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

If you want just the values:

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

And last note: using dict as a variable name overwrites the built in dict and makes it unavailable in your code.

CodePudding user response:

Typically, I would like to use slice notation to do this, but dict.items() returns an iterator, which is not slicable.

You have two main options:

  1. Make it something that slice notation works on:
x = {'a':1, 'b':2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
for item, index in list(x.items())[:5]:
  print(item)
  1. Use something that works on iterators. In this case, the built-in (and exceedingly popular itertools package)
import itertools
x = {'a':1, 'b':2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
for item in itertools.islice(x, 5):
  print(item)
  • Related