[Python] Python dictonary convert keys to values and vice versa

Discussão em 'Python' iniciado por Stack, Agosto 11, 2025.

  1. Stack

    Stack Membro Participativo

    I need to convert keys to values and values to key.. i am using python 2.7 version... if there is any better approach then this let me know

    source_info=\
    {'benz': 'car',
    'audi': 'car',
    'bmw': 'car',
    'toyata': 'car',
    'ferrai': 'car',
    'ducati': 'bike',
    'suzki': 'bike',
    'yamaha': 'bike'
    }

    def format_data(source_info=None):
    # {} converting to set
    id_unique = {source_info[key_id] for key_id in source_info}
    result_dict = {}
    # Result data from seq_def with searching for key with algos
    for key in id_unique:
    vechile_name = {k: v for k, v in source_info.items() if v in [key]}
    result_dict[key] = list(vechile_name.keys())
    return result_dict

    result = format_data(source_info)
    print(result)


    I'm using the above code to get my job done.. but wanted to know if there is any better approach then this ?

    result looks like this:

    {'bike': ['ducati', 'suzki', 'yamaha'], 'car': ['benz', 'audi', 'bmw', 'toyata', 'ferrai']}


    Highly appreciate your inputs here...

    Continue reading...

Compartilhe esta Página