Lucas Aimaretto
Lucas Aimaretto

Reputation: 1489

Get inner nested dictionary with key stored in list

I have this list:

n = ['FAKE0.0.1.8', '10.2.2.22', '10.2.182.10', '10.2.20.5', '10.2.94.135', '10.2.110.1', '10.2.94.73', '10.2.20.1', '10.2.94.38', '10.2.94.37', '10.2.7.121']

And this dictionary:

i = {'10.2.94.38': {'area': '0.0.1.8'}}

As you can see, there is only one item inside the list, which is a valid key for the dictionary: 10.2.94.38.

If I do the following, I can get the inner diciontary {'area':'0.0.1.8'}:

>>> [i.get(x,'NA') for x in n]
['NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', {'area': '0.0.1.8'}, 'NA', 'NA']

If I do the following, I can get the value 0.0.1.8, as usual:

>>> i[n[8]]['area']
'0.0.1.8'

The problem I'm facing is that I cannot reach the ultimate value 0.0.1.8. I've tried the following without success:

>>> [i.get(x['area'],'NA') for x in n]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
TypeError: string indices must be integers

How can I do it? The final result that I want to achieve is:

['NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', '0.0.1.8', 'NA', 'NA']

Thanks!

Lucas

Upvotes: 1

Views: 52

Answers (2)

Aaditya Ura
Aaditya Ura

Reputation: 12689

This is very simple , don't make it complicated:

n = ['FAKE0.0.1.8', '10.2.2.22', '10.2.182.10', '10.2.20.5', '10.2.94.135', '10.2.110.1', '10.2.94.73', '10.2.20.1', '10.2.94.38', '10.2.94.37', '10.2.7.121']
i = {'10.2.94.38': {'area': '0.0.1.8'}}

print([i[x]['area'] if x in i else 'NaN' for x in n])

output:

['NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', '0.0.1.8', 'NaN', 'NaN']

If you only want values then you can also filter the result:

n = ['FAKE0.0.1.8', '10.2.2.22', '10.2.182.10', '10.2.20.5', '10.2.94.135', '10.2.110.1', '10.2.94.73', '10.2.20.1', '10.2.94.38', '10.2.94.37', '10.2.7.121']
i = {'10.2.94.38': {'area': '0.0.1.8'},'10.2.2.22':{'area': '0.0.1.9'}}


print(list(map(lambda x:i[x]['area'],filter(lambda x:x in i,n))))

output:

['0.0.1.9', '0.0.1.8']

Upvotes: 0

jpp
jpp

Reputation: 164823

One way is to use try / except:

n = ['FAKE0.0.1.8', '10.2.2.22', '10.2.182.10', '10.2.20.5', '10.2.94.135',
     '10.2.110.1', '10.2.94.73', '10.2.20.1', '10.2.94.38', '10.2.94.37', '10.2.7.121']

i = {'10.2.94.38': {'area': '0.0.1.8'}}

def try_get_all(i, n):
    for j in n:
        try:
            yield i[j]['area']
        except KeyError:
            yield 'NA'

res = list(try_get_all(i, n))

# ['NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', '0.0.1.8', 'NA', 'NA']

Upvotes: 1

Related Questions