1

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Use name, value = my_dict.popitem()

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.