Home > Net >  Accessing second element of tuple-key in a nested dictionary in python
Accessing second element of tuple-key in a nested dictionary in python

Time:03-31

I have a dictionary as follows:-

Diction = {'stars': {(s4, s3): (2, 3), (s3, s4): (3, 2), (s3, s2): (2, 3), (s2, s3): (3, 2), (s2, s1): (2, 2),(s1, s2): (2, 2), (h1, s1): (0, 1), (s1, h1): (1, 0),(h2, s2): (0, 1), (s2, h2): (1, 0), (h3, s3): (0, 1),(s3, h3): (1, 0), (h4, s4): (0, 1), (s4, h4): (1, 0)}}

Now value for key 'stars' is another dictionary. In this dictionary if I know first elements of tuple-key and tuple value (for ex s4 and 2 for first item), Is it possible to access second element of tuple key i.e. s3?

CodePudding user response:

With list comprehension:

>>> [k[1] for k, v in Diction["stars"].items() if k[0]=="s4" and v[0]==2]
['s3']

CodePudding user response:

I'm not sure how much help this will be, but you could iterate over the .items() of your (inner) dictionary, which will give you (key, value) pairs as tuples.

This search function is basically just doing that, with inline unpacking:

def search(d, sk0, sv0):
    for ((k0, k1), (v0, _)) in d.items():
        if k0 == sk0 and v0 == sv0:
            return k1
print(search(Diction['stars'], s4, 2))  # -> s3

I have no idea what the variables are, so I used k0,k1 for the key components and v0 for the first value component, but you'd probably want to use something more clear.

  • Related