从Python字典中读取是否可能不存在密钥 [英] Reading from Python dict if key might not be present

查看:99
本文介绍了从Python字典中读取是否可能不存在密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python和解析数据非常陌生.

I am very new to Python and parsing data.

我可以将外部JSON提要放入Python字典中并在字典上进行迭代.

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

for r in results:
     print r['key_name']

当我浏览返回的结果时,如果键没有值(记录中的值可能并不总是存在),则会出现错误.如果我打印结果,则显示为

As I walk through the results returned, I am getting an error when a key does not have a value (a value may not always exist for a record). If I print the results, it shows as

'key_name': None, 'next_key':.................

我的代码因错误而中断.如何控制没有值的键?

My code breaks on the error. How can I control for a key not having a value?

任何帮助将不胜感激!

布鲁克

推荐答案

适用的首选方法:

for r in results:
     print r.get('key_name')

如果key_name不是字典中的键,则仅打印None.您还可以使用其他默认值,只需将其作为第二个参数传递即可:

this will simply print None if key_name is not a key in the dictionary. You can also have a different default value, just pass it as the second argument:

for r in results:
     print r.get('key_name', 'Missing: key_name')

如果您想做一些与使用默认值不同的事情(例如,在没有键的情况下完全跳过打印),那么您需要更多的结构,即:

If you want to do something different than using a default value (say, skip the printing completely when the key is absent), then you need a bit more structure, i.e., either:

for r in results:
    if 'key_name' in r:
        print r['key_name']

for r in results:
    try: print r['key_name']
    except KeyError: pass

第二个可以更快(如果它相当稀有,而缺少一个键),但是对于许多人来说,第一个看起来更自然.

the second one can be faster (if it's reasonably rare than a key is missing), but the first one appears to be more natural for many people.

这篇关于从Python字典中读取是否可能不存在密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆