Idiomatic way to get key from a one-item Python dict not knowing this key (but knowing the dict has only one item)?

Viewed 52

I have a list of one-item dicts (parsed from JSON) that looks like this:

lst = [
{"key_0": "value_0"},
{"key_1": "value_1"},
{"key_2": "value_2"},
...
{"key_n": "value_n"}
]

what would be the most elegant way to retrieve a key from the list's n-element not knowing this key?

I came up with:

[*lst[n].keys()][0]

but it looks somewhat ugly to me.

2 Answers

You can create an iterator from the dict and use the next function to obtain the first item:

next(iter(lst[n]))

You can convert direct keys to list and then get first item

>>> n = 0
>>> list(lst[n])[0]
'key_0'
Related