Reading from Python dict if key might not be present

后端 未结 7 463
清酒与你
清酒与你 2021-01-30 17:10

I am very new to Python and parsing data.

I can pull an external JSON feed into a Python dictionary and iterate over the dictionary.

for r in results:
         


        
相关标签:
7条回答
  • 2021-01-30 17:55

    There are two straightforward ways of reading from Python dict if key might not be present. for example:

    dicty = {'A': 'hello', 'B': 'world'}

    1. The pythonic way to access a key-value pair is:

    value = dicty.get('C', 'default value')

    1. The non-pythonic way:

    value = dicty['C'] if dicty['C'] else 'default value'

    1. even worse:

    try: value = dicty['C'] except KeyError as ke: value = 'default value'

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