Sid
Sid

Reputation: 4055

Check if value exists in a dictionary of dictionaries and get the key(s)?

I have a dictionary of dictionaries:

x = {'NIFTY': {11382018: 'NIFTY19SEPFUT', 13177346: 'NIFTY19OCTFUT', 12335874: 'NIFTY19NOVFUT'}}

The dictionary has a lot of other dictionaries inside.

I want to check whether example:

y = 11382018

exists in the dictionary, if yes, get the master key in this case NIFTY and the value of the above key i.e. 'NIFTY19SEPFUT'

I can do this in the following way I assume:

for key in x.keys():
    di = x[key]
    if y in di.keys():
       inst = key
       cont = di[y]

Just wondering if there is a better way.

I was thinking along the lines of not having to loop over the entire dictionary master keys

Upvotes: 2

Views: 1449

Answers (3)

Austin
Austin

Reputation: 26039

More compact version (generic):

[(k, v[y]) for k, v in d.items() if y in v]

Or:

*next(((k, v[y]) for k, v in d.items() if y in v), 'not found')

if you can guarantee the key is found only in one nested dictionary. (Note that I have used d as dictionary here, simply because that feels more meaningful)

Code:

d = {'NIFTY': {11382018: 'NIFTY19SEPFUT', 13177346: 'NIFTY19OCTFUT', 12335874: 'NIFTY19NOVFUT'}}

y = 11382018
print([(k, v[y]) for k, v in d.items() if y in v])

# or:
# print(*next(((k, v[y]) for k, v in d.items() if y in v), 'not found'))

Upvotes: 2

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Straightforwardly (for only 2 levels of nesting):

x = {'NIFTY': {11382018: 'NIFTY19SEPFUT', 13177346: 'NIFTY19OCTFUT', 12335874: 'NIFTY19NOVFUT'}}
search_key = 11382018
parent_key, value = None, None

for k, inner_d in x.items():
    if search_key in inner_d:
        parent_key, value = k, inner_d[search_key]
        break

print(parent_key, value)   # NIFTY NIFTY19SEPFUT

Upvotes: 1

yatu
yatu

Reputation: 88236

A more compact way to retrieve both values of interest would be using a nested dictionary comprehension:

[(k, sv) for k,v in x.items() for sk,sv in v.items() if sk == y]
# [('NIFTY', 'NIFTY19SEPFUT')]

Upvotes: 2

Related Questions