Concise Way To Access A Dictionary Value When The Key Is Unknown
I have a bunch of big dictionaries with keys that are strings of text. Each key value pair has an identical format. I frequently end up needing to print out one of the values to
Solution 1:
Since you are using Python 3 (where dict.values
does not return a full fledged list), you can get an arbitrary value in a memory efficient way with
next(iter(d.values()))
If there's a chance that the dictionary might have no values, wrap it in a helper function that catches the StopIteration
, i.e.:
def get_arb_value(dic):
try:
return next(iter(dic.values()))
except StopIteration:
# do whatever you like
The Python 2 equivalent of next(iter(dic.values()))
would be next(dic.itervalues())
.
Solution 2:
You could simply do this:
list(d.values())[0]
In other words, take all the values, convert to a list, take the first one.
Post a Comment for "Concise Way To Access A Dictionary Value When The Key Is Unknown"