0

Using Python 3, I would like to get an element (any element) from a dict without making a list of all of the elements.

In Python 2, I did this:

next(foo.itervalues())

In Python 3, none of these work:

next(foo.values())
next(foo.items())
next(foo)

Of course I can do this:

list(foo.values())[0]

but that makes a list of the whole dict before returning the first one.

You cannot assume that I know a key. Also, the dictionary may not be altered.

Jim Hunziker
  • 14,111
  • 8
  • 58
  • 64
  • 2
    `next()` requires an iterator, `foo.value()` is only iterable, use `iter()` to make produce an iterator for it: `next(iter(foo.values()))`. – Martijn Pieters Dec 05 '16 at 17:19
  • Your question is most certainly a duplicate, though. For example [Choose one key arbitrarily in a dictionary without iteration](http://stackoverflow.com/q/37942550/2301450) – vaultah Dec 05 '16 at 17:21
  • I'll take that one, @vaultah . Thanks! – Jim Hunziker Dec 05 '16 at 17:22
  • 1
    @JimHunziker: I didn't dupe to the same post. I duped to a *different* post, one that explains why `next(iter(foo.values()))` works. – Martijn Pieters Dec 05 '16 at 17:23
  • That's fine, @MartijnPieters - the original dupe pointed to was something about getting a random element, but I see you changed it. – Jim Hunziker Dec 05 '16 at 17:25

0 Answers0