Reading from Python dict if key might not be present

后端 未结 7 471
清酒与你
清酒与你 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:48

    [Updated to remove careless mistake]

    You could also do something like this:

    for r in (row for row in results if 'a' in row):
        print r['a']
    

    This uses a generator expression to pick "rows" out of "results" where "row" includes the key "a".

    Here's a little test script:

    results = [{'a':True}, {'b':True}, {'a':True}]
    for r in (row for row in results if 'a' in row): print r['a']
    

提交回复
热议问题