I have stumbled across a problem with python dictionary keys.
For instance, I have a dictionary:
foo = {
'longkey': 1,
'shortkey': 2,
}
How can I return 2
from foo
using just the string 'short'
?
I have stumbled across a problem with python dictionary keys.
For instance, I have a dictionary:
foo = {
'longkey': 1,
'shortkey': 2,
}
How can I return 2
from foo
using just the string 'short'
?
If you want to return 2
just with the string short
, you can do like this:
for k,v in foo.items():
if 'short' in k:
print(v)
This will print the value
of key short
if any key of dictionary contains the word short
.
If you want that the key
should start with short
, you can try this:
for k,v in foo.items():
if k.startswith('short'):
print(v)