Intrastellar Explorer
Intrastellar Explorer

Reputation: 2511

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

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?

Upvotes: 1

Views: 1195

Answers (2)

Markus Hirsimäki
Markus Hirsimäki

Reputation: 745

Use name, value = my_dict.popitem()

>>> my_dict = {"unknown_key_name": 1}
>>> name, value = my_dict.popitem()
>>> name
'unknown_key_name'
>>> value
1
>>>

Upvotes: 2

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.

Upvotes: 4

Related Questions