Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dict.get() with multidimensional dict?

Tags:

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.

like image 681
user2034412 Avatar asked Apr 14 '13 19:04

user2034412


People also ask

Can you explain the dict get () function?

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.

How do you get a value from a nested dictionary?

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 ).

How do you access a multi level dictionary in Python?

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.

Should I use dict () or {}?

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.


2 Answers

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}             }) 
like image 58
Pavel Anossov Avatar answered Nov 01 '22 15:11

Pavel Anossov


Another way to get multidimensional dict example ( use get method twice)

d.get('a', {}).get('j') 
like image 22
Hafiz Muhammad Shafiq Avatar answered Nov 01 '22 16:11

Hafiz Muhammad Shafiq