Python 3 how to get value from dictionary containing only one key-value pair with unknown key?

Question:

Hello Stack Overflow,

What is the most readable + simplest way to get a value from a dictionary that only contains one key-value pair?

Note: I do not know what the key is when I try to fetch the value, it’s autogenerated.

Let’s imagine the dictionary to look something like this:

my_dict = {
    "unknown_key_name": 1
}

FYI I am using Python 3.6. My current solution is this: val = list(my_dict.values())[0]

I just have a feeling there is a more “elegant” solution, does anyone know of one?

Answers:

Get the iterator for values then use the next call to get the first value:

my_dict = {
    "unknown_key_name": 1
}

first_val = next(iter(my_dict.values()))

print(first_val) # 1

This won’t put a list into memory just to get the first element.

Use name, value = my_dict.popitem()

>>> my_dict = {"unknown_key_name": 1}
>>> name, value = my_dict.popitem()
>>> name
'unknown_key_name'
>>> value
1
>>>
Answered By: Markus Hirsimäki
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.