def query_complex_dict(dictionary, preferred_key, key, secondary_key_list=[]):
    """dictionary is a dictionary of dictionaries with multiple level hierarchies (often related to json file)
    preferred_key and key are the first-level key
    When preferred_key is available, use it instead of key
    Assume at least one of them can satisfy the query of key_list
    
    Examples:
        d = {'global': {'level1': {'level2': {'level3': 999}}}, 'file1': {}}
        assert query_complex_dict(d, preferred_key='global', key='file1', secondary_key_list=['level1', 'level2', 'level3']) == 999
    """
    if preferred_key in dictionary:
        ans = dictionary[preferred_key]
        for k in secondary_key_list:
            if k in ans:
                ans = ans[k] # ans could end up to be {}, [], '', or None
            else:
                ans = None
                break
    else:
        ans = None
    if ans is None or ans=={} or ans=='' or ans==[]:
        ans = dictionary[key]
        for k in secondary_key_list:
            ans = ans[k]
    return ans