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} }
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.
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.
get()—method comes in: it returns the value for a specified key in a dictionary. This method will only return a value if the specified key is present in the dictionary, otherwise it will return None.
Access Values using get() Another way to access value(s) in a nested dictionary ( employees ) is to use the dict. get() method. This method returns the value for a specified key. If the specified key does not exist, the get() method returns None (preventing a KeyError ).
Access Nested Dictionary Items You can access individual items in a nested dictionary by specifying key in multiple square brackets. If you refer to a key that is not in the nested dictionary, an exception is raised. To avoid such exception, you can use the special dictionary get() method.
With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.
How about
d.get('a', {'j': 'NA'})['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
Same idea using 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} })
Another way to get multidimensional dict example ( use get method twice)
d.get('a', {}).get('j')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With