Accessing Python dict values with the key start characters

后端 未结 7 1495
南笙
南笙 2020-12-28 13:56

I was wondering: would it be possible to access dict values with uncomplete keys (as long as there are not more than one entry for a given string)? For example:



        
相关标签:
7条回答
  • 2020-12-28 14:21
    >>> my_dict = {'name': 'Klauss', 'age': 26, 'Date of birth': '15th july'}
    >>> next(v for k,v in my_dict.items() if 'Date' in k)
    '15th july'
    
    
    >>> [ v for k,v in my_dict.items() if 'Date' in k]
    ['15th july']
    
    
    >>> next( v for k,v in my_dict.items() if k.startswith('Date'))
    '15th july'
    >>> [ v for k,v in my_dict.items() if k.startswith('Date')]
    ['15th july']
    

    if i use the above given method i am getting StopIteration exception

    0 讨论(0)
提交回复
热议问题