Reputation: 2511
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
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
Reputation: 7897
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