4

Imagine I have a dict like this:

d = {'key': 'value'}

The dict contains only one key value. I am trying to get key from this dict, I tried d.keys()[0] but it returns IndexError, I tried this:

list(d.keys())[0]

It works just fine but I think it is not a good way of doing this because it creates a new list and then get it first index.
Is there a better way to do this? I want to get the value too.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59

3 Answers3

6

If you know (or expect) there is exactly one key / value pair then you could use unpacking to get the key and the value. eg.

[item] = d.items()
assert item == ('key', 'value')

You can take this one step further and unpack the key / value pair too.

[[k, v]] = d.items()
assert k == 'key'
assert v == 'value'

Of course this throws an error if the dictionary has multiple key / value pairs. But then this is useful. Dictionaries are unordered pre python 3.7 (dict is ordered in CPython 3.6, but it's an implementation detail), so doing list(d.items())[0] can give inconsistent results. Even in 3.7+ the ordering is over insertion, not any natural ordering of the keys, so you could still get surprising results.

Dunes
  • 37,291
  • 7
  • 81
  • 97
2

You can do it the silly way:

def silly(d:dict):
    for k,v in d.items():
        return (k,v) # will only ever return the "first" one 
                     # with 3.7 thats the first inserted one

Using

list(d.items())[0]

at least gives you key and value at once (and throw on empty dicts).

With dictionarys being "insert-ordered" from 3.7 onwards there might evolve some methods to "get the first" or "get the last" of it, but so far dict were unordered and indexing into them (or getting first/last) made no sense.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
-2

There is some information for you below, but I believe that you don't fully understand dictionaries. They are unsorted, meaning that the list created will be in random order, so indexing will return unpredictable answers.

Since Python 3, d.keys() no longer returns a list, and instead returns a dictionary object which doesn't support indexing and subsequently would return IndexError. Unfortunately, you will simply have to use list().

If the option is available (i.e. You are going to loop through the list), you could go:

for item in d.keys():
    # Do something

which means that you don't have to convert it to a list.

Elodin
  • 650
  • 5
  • 23