Skip to main content
 首页 » 编程设计

python之如果它在 python 的字典中有相似/相同的键,如何检查值

2025年05月04日9kenshinobiy

如果键在 dict 中有 'extra_',我如何检查值?

这是我所做的:

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

提前致谢...

请您参考如下方法:

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 .