0

Say I have the following dictionary,

d = {'foo': 1,
     'bar': 2,
     'baz:foo', 3,
     'baz:bar', 4
    }

and I want to find whether any 'baz' keys exist in the dict. I have the following, which works fine.

for key in d:
    if key.startswith('baz'):
        do_something()
        break

I would prefer something like the following:

if 'baz*' in d:
    do_something()

but I haven't been able to make it work.

Is there a better way to search for partial keys in a python dictionary?

mitchute
  • 389
  • 1
  • 3
  • 10
  • I think your solution is best of a bad data structure, maybe a better dictionary structure would be like `{'baz':{'':2, 'foo':3, 'bar':4}}` – Chris_Rands Aug 30 '17 at 14:52
  • also you didn't properly format your dictionary in your post – gold_cy Aug 30 '17 at 14:52
  • Check if there is a key in the dictionary with a if **Hi, I wish this is what you was looking for... see ya.** d = {'foo': 1, 'bar': 2, 'baz:foo': 3, 'baz:bar': 4 } if [k for k in d if k.startswith("bar")]: print("Ok, I found it") >output Ok, I found it >>> – PythonProgrammi Aug 30 '17 at 15:03

0 Answers0