如果密钥在'extra_'
中有dict
?
这就是我所做的:
>>> 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'
>>>
如果dict
具有'extra_'
之类的密钥,那么这就是我想要输出的内容:
u'extra_test1' : [u'jknj']
u'extra_test2' : [u'jnjl']
提前感谢...
答案 0 :(得分: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']}
其中d
是你的字典。我已将其重命名,因此它不会影响builtin。
答案 1 :(得分:3)
使用词典理解:
>>> {k: v for k,v in d.iteritems() if k.startswith('extra_')}
{u'extra_test1': [u'jknj'], u'extra_test2': [u'jnjl']}
答案 2 :(得分:2)
唯一的方法是迭代密钥并测试它们:
for key in dict_.iterkeys():
if key.startswith('extra_'):
...
答案 3 :(得分:2)
for k in your_dict:
if k.startswith('extra_'):
print '%r : %r' % (k, your_dict[k])