Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problems with double .get() in dictionary

I’m working with a nested dictionary were the entries looks like this:

net_info = {
            '17052242':{'lengthkm': 1.555787, 'uparea': 123.23709555834532, 'order': 2,
                        'strmDrop_t': 231.5, 'unitarea': 123.23709555834532},
            '21009006':{'lengthkm': 6.677901703662528,'uparea': 493.8188826654188,
                        'order': 2,'strmDrop_t': 5.3, 'unitarea': 36.89608111068623},
            .
            .
            .
             }

Here is a line of code where I look for a key and a feature inside the dictionary using a double .get(). It works like a charm except when it can’t find the key… I know it is because it is passing 0 as a key to the next .get(). My question is, is there a way to just return 0 if it can’t find the key and not pass it to the next .get()?

unitarea_max = max(net_dictionary.get(in1,0).get('unitarea',0), \
net_dictionary.get(in2,0).get('unitarea',0))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to pass a dictionary to the next .get(). Since it’s an empty dictionary you’ll get the default from the second .get().

net_dictionary.get(in1,{}).get('unitarea',0)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading