-1

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'?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Neykuratick
  • 127
  • 4
  • 14
  • [https://stackoverflow.com/questions/10795973/python-dictionary-search-values-for-keys-using-regular-expression] .Please check this link. – Dinesh Kumar Oct 26 '21 at 20:21
  • 1
    You would have to iterate through all key-value-pairs of the dict to find that key or you use another data structure (maybe from external library) to find it more efficiently. – Michael Butscher Oct 26 '21 at 20:22
  • 1
    keys = [key for key in foo if key.startswith('short')] Use this – Deepak Tripathi Oct 26 '21 at 20:22
  • 2
    Why do you want to do this? What are the actual values of `longkey` and `shortkey`? Can you not just assign `foo["short"] = 2` and access your dictionary normally? Having to iterate over the keys defeats the purpose of a dictionary. – ddejohn Oct 26 '21 at 20:25
  • 3
    One of the purposes of a dictionary is to have hashed keys, and thus O(1) access to the data. If you need to loop over the keys to find the one you need, then this defeats the purpose of a dictionary. Can you explain in more details why you need to do this? – mozway Oct 26 '21 at 20:26

1 Answers1

1

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)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Rakesh Poddar
  • 183
  • 3
  • 11