在Python中处理未声明的dict键 [英] Handle undeclared dict key in Python

查看:99
本文介绍了在Python中处理未声明的dict键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  c = {:sample = > 1,另一个=> 2} 

我可以这样处理表:

  [c [:sample] .nil? ,c [:另一个] .nil? ,c [:not_in_list] .nil?] 

我试图在Python中做同样的事情。我创建了一个新的字典:

  c = {sample:1,另一个:2} 

我无法处理以下的零价值异常:

  c [not-in-dictionary] 

这个:

  c [:not_in_dictionery]不是无

它返回一个异常,而不是 False。我该如何处理?

解决方案

在您特定的情况下,您应该可以执行此操作,而不是与

  c 


$ b $中的not_in_dictionary b

如果你真的使用这个代码,它将不起作用:

  c [:not_in_dictionary]不是无

Python没有特殊的关键字字典键;使用普通字符串。






Python中的普通行为是在请求缺少的键时引发异常,让你处理例外。

  d = {a :2,c:3} 

try:
print d [b]
除了KeyError:
print我们没有b字典!

如果要获取如果缺少值,您可以使用 dict .get 方法返回值(没有默认情况下)如果密钥缺失。

  print d .jpg(a)#打印2 
打印d.get(b)#prints无
打印d.get(b,0)#打印0

只需检查一个键是否具有 dict 中的值,请使用中的不在关键字中。

打印a在d#中
打印c不在d#False
打印d不在d#True






Python包含一个模块,允许您定义在正常使用时返回默认值而不是错误的字典: collections.defaultdict 。你可以这样使用:

  import collections 

d = collections $ d
print d [b]#无
打印d [b] ==无#True
打印bin d#True

请注意与。当你第一次查找一个密钥时,它会将它指向默认值,所以现在它被认为是 dict


In my Ruby application I have a hash table:

c = {:sample => 1,:another => 2}

I can handle the table like this:

[c[:sample].nil? , c[:another].nil? ,c[:not_in_list].nil?]

I'm trying to do the same thing in Python. I created a new dictionary:

c = {"sample":1, "another":2}

I couldn't handle the nil value exception for:

c["not-in-dictionary"]

I tried this:

c[:not_in_dictionery] is not None

and it is returning an exception instead of False. How do I handle this?

解决方案

In your particular case, you should probably do this instead of comparing with None:

"not_in_dictionary" in c

If you were literally using this code, it will not work:

c[:not_in_dictionary] is not None

Python doesn't have special :keywords for dictionary keys; ordinary strings are used instead.


The ordinary behaviour in Python is to raise an exception when you request a missing key, and let you handle the exception.

d = {"a": 2, "c": 3}

try:
    print d["b"]
except KeyError:
    print "There is no b in our dict!"

If you want to get None if a value is missing you can use the dict's .get method to return a value (None by default) if the key is missing.

print d.get("a") # prints 2
print d.get("b") # prints None
print d.get("b", 0) # prints 0

To just check if a key has a value in a dict, use the in or not in keywords.

print "a" in d # True
print "b" in d # False
print "c" not in d # False
print "d" not in d # True


Python includes a module that allows you to define dictionaries that return a default value instead of an error when used normally: collections.defaultdict. You could use it like this:

import collections

d = collections.defaultdict(lambda: None)
print "b" in d # False
print d["b"] # None
print d["b"] == None # True
print "b" in d # True

Notice the confusing behaviour with in. When you look up a key for the first time, it adds it pointing to the default value, so it's now considered to be in the dict.

这篇关于在Python中处理未声明的dict键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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