Home > other >  How do I access multiple keys in python dictionary
How do I access multiple keys in python dictionary

Time:10-08

I have a dictionary

my_dict = { 
    ('X', 'A'): 5,
    ('X', 'B'): 2,
    ('Y', 'B'): 3,
    ('Z', 'A'): 3,
    ('Z', 'C'): 4,
    }

My goal is to see what are the keys 'X' are pared with. For this example it should return ['A', 'B']. However, order matters. So, 'A' should return None.

How can I break up the multi-valued keys to achieve that?

CodePudding user response:

How can I break up the multi-valued keys to achieve that?

Why not just have a 2-level dictionary?

In your current dict, 'X' isn't a key, and because Python does not have a built-in btree (or other tree-based map) you can't select map subsets, however by making the two-level keys into two levels of keys:

my_dict = { 
    'X': {
        'A': 5,
        'B': 2,
    },
    'Y': {
        'B': 3,
    },
    'Z': {
        'A': 3,
        'C': 4,
    },
}

You get exactly what you need:

  • the values for (X, A) are at my_dict['X']['A']
  • the sub-keys for Z are at my_dict['Z'].keys()
  • all the values for Y (regardless of keys) are at my_dict['Y'].values()
  • key might be missing? Use dict.get e.g. my_dict.get('A') => None, whereas my_dict['Y'] => {'B': 3}

CodePudding user response:

I found the solution. Turns out that the multivalued keys in python are saved as an array. So you can just use my_key[0] to return the first value of the key and my_key[1] to return the second value of the key.

CodePudding user response:

This should work for what you are trying to achieve

my_dict = { 
    ('X', 'A'): 5,
    ('X', 'B'): 2,
    ('Y', 'B'): 3,
    ('Z', 'A'): 3,
    ('Z', 'C'): 4,
    }
array = []
def getPair(value):
    for x in my_dict:
        if x[0] == value:
            array.append(x[1])
    return array;
            
        
print(getPair('X'))

CodePudding user response:

You can achieve that with list destructuring :

for (key1,key2),value in my_dict.items() :
    print(f"{key1},{key2}:{value}")
    if key1 == 'X' :
        print(f"X paired with {key2}, has value {value}")

If you only care about the keys:

for key1,key2 in my_dict.keys() :
    if key1 == 'X' :
        print(f"X paired with {key2}")

Performance-wise it iterates over the whole dictionary keys so it is not the most efficient but it is acceptable if you don't have a huge dictionary and it is unavoidable with your data structure.

If you need better performance structure the data with a 2 layer nested dictionary { key1: {key2 : value , ... }, ... } and then just access my_dict[key1] as suggested by Masklinn.

  • Related