Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a dict key and value [duplicate]

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.

like image 433
Mehrdad Pedramfar Avatar asked Oct 30 '25 00:10

Mehrdad Pedramfar


2 Answers

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.

like image 194
Dunes Avatar answered Nov 01 '25 13:11

Dunes


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.

like image 41
Patrick Artner Avatar answered Nov 01 '25 13:11

Patrick Artner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!