如何将dict.get()与多维dict一起使用? [英] How to use dict.get() with multidimensional dict?
问题描述
我有一个多维字典,我希望能够通过key:key对来检索值,如果第一个键不存在,则返回'NA'.所有子小格都具有相同的键.
I have a multidimensional dict, and I'd like to be able to retrieve a value by a key:key pair, and return 'NA' if the first key doesn't exist. All of the sub-dicts have the same keys.
d = { 'a': {'j':1,'k':2},
'b': {'j':2,'k':3},
'd': {'j':1,'k':3}
}
我知道我可以使用 d.get('c','NA')
来获取子字典(如果存在),否则返回'NA',但是我真的只需要一个值从子命令.我想做类似 d.get('c ['j']','NA')
的事情.
I know I can use d.get('c','NA')
to get the sub-dict if it exists and return 'NA' otherwise, but I really only need one value from the sub-dict. I'd like to do something like d.get('c['j']','NA')
if that existed.
现在,我只是检查顶级键是否存在,然后将子值(如果存在)分配给变量,如果不存在,则将其分配给'NA'
.但是,我这样做大约有50万次,并且还从其他地方检索/生成有关每个顶级密钥的其他信息,我正在尝试加快这一速度.
Right now I'm just checking to see if the top-level key exists and then assigning the sub-value to a variable if it exists or 'NA'
if not. However, I'm doing this about 500k times and also retrieving/generating other information about each top-level key from elsewhere, and I'm trying to speed this up a little bit.
推荐答案
如何
d.get('a', {'j': 'NA'})['j']
?
如果不是所有下属都具有 j
键,则
If not all subdicts have a j
key, then
d.get('a', {}).get('j', 'NA')
要减少创建的相同对象,可以设计类似
To cut down on identical objects created, you can devise something like
class DefaultNASubdict(dict):
class NADict(object):
def __getitem__(self, k):
return 'NA'
NA = NADict()
def __missing__(self, k):
return self.NA
nadict = DefaultNASubdict({
'a': {'j':1,'k':2},
'b': {'j':2,'k':3},
'd': {'j':1,'k':3}
})
print nadict['a']['j'] # 1
print nadict['b']['j'] # 2
print nadict['c']['j'] # NA
使用 defaultdict
的相同想法:
import collections
class NADict(object):
def __getitem__(self, k):
return 'NA'
@staticmethod
def instance():
return NADict._instance
NADict._instance = NADict()
nadict = collections.defaultdict(NADict.instance, {
'a': {'j':1,'k':2},
'b': {'j':2,'k':3},
'd': {'j':1,'k':3}
})
这篇关于如何将dict.get()与多维dict一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!