I saw How to extract dictionary single key-value pair in variables suggesting:
d = {"a":1} (k, v), = d.items()
But: I only care about the value. And I want to pass that value to a method; like:
foo(v)
So the question is: is there a simple command that works for both python2 and python3 that gives me that value directly, without the detour of the "tuple" assignment?
Or is there a way to make the tuple assignment work for my usecase of calling a method?
Use dict. get() to get the default value for non-existent keys. You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist.
Method 1 : Using List. Step 1: Convert dictionary keys and values into lists. Step 2: Find the matching index from value list. Step 3: Use the index to find the appropriate key from key list.
list(d.values())[0]
will be evaluated to 1. As pointed out in the comments, the cast to list
is only needed in python3.
next(iter(d.values()))
is another possibility (probably more memory efficient, as you do not need to create a list)
Both solution testes locally with python 3.6.0 and in TIO with python 2.
next(iter(d.values()))
is the natural way to extract the only value from a dictionary. Conversion to list
just to extract the only element is not necessary.
It is also performs best of the available options (tested on Python 3.6):
d = [{'a': i} for i in range(100000)] %timeit [next(iter(i.values())) for i in d] # 50.1 ms per loop %timeit [list(i.values())[0] for i in d] # 54.8 ms per loop %timeit [list(i.values()).pop() for i in d] # 81.8 ms per loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With