1

how can I check values if the key has 'extra_' in dict?

this what I have done :

>>> dict =  { u'last_name': [u'hbkjh'], u'no_of_nights': [u'1'], u'check_in': [u'2012-03-19'], u'no_of_adult': [u'', u'1'], u'csrfmiddlewaretoken': [u'05e5bdb542c3be7515b87e8160c347a0'], u'memo': [u'kjhbn'], u'totalcost': [u'1800.0'], u'product': [u'4'], u'exp_month': [u'1'], u'quantity': [u'2'], u'price': [u'900.0'], u'first_name': [u'sdhjb'], u'no_of_kid': [u'', u'0'], u'exp_year': [u'2012'], u'check_out': [u'2012-03-20'], u'email': [u'ebmalifer@agile.com.ph'], u'contact': [u'3546576'], u'extra_test1': [u'jknj'], u'extra_test2': [u'jnjl'], u'security_code': [u'3245'], u'charged': [u'200.0']}
>>> for x in dict:
...  x
... 
u'totalcost'
u'check_in'
u'last_name'
u'extra_test2'
u'memo'
u'extra_test1'
u'product'
u'email'
u'charged'
u'no_of_nights'
u'no_of_kid'
u'contact'
u'exp_month'
u'first_name'
u'no_of_adult'
u'csrfmiddlewaretoken'
u'exp_year'
u'check_out'
u'price'
u'security_code'
u'quantity'
>>> 

this is what i want to be the output if dict has key like 'extra_':

u'extra_test1' : [u'jknj']
u'extra_test2' : [u'jnjl']

thanks in advance ...

wim
  • 338,267
  • 99
  • 616
  • 750
gadss
  • 21,687
  • 41
  • 104
  • 154

4 Answers4

6
In [4]: dict((k,v) for k,v in d.items() if k.startswith('extra_'))
Out[4]: {u'extra_test1': [u'jknj'], u'extra_test2': [u'jnjl']}

where d is your dictionary. I've renamed it so it doesn't shadow the builtin.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • You can use dict comprehension syntax in Python 2.7 and up to make the code a little more readable. See [this question's answer](http://stackoverflow.com/a/1747827/446456). – eksortso Feb 29 '12 at 10:56
3

Use a dict comprehension:

>>> {k: v for k,v in d.iteritems() if k.startswith('extra_')}
{u'extra_test1': [u'jknj'], u'extra_test2': [u'jnjl']}
wim
  • 338,267
  • 99
  • 616
  • 750
2

The only way is to iterate over the keys and test them:

for key in dict_.iterkeys():
    if key.startswith('extra_'):
        ...
warvariuc
  • 57,116
  • 41
  • 173
  • 227
2
for k in your_dict:
    if k.startswith('extra_'):
        print '%r : %r' % (k, your_dict[k])
Amber
  • 507,862
  • 82
  • 626
  • 550