[Python] update then rearrange list of dictionaries in python [closed]

Discussão em 'Python' iniciado por Stack, Maio 3, 2025.

  1. Stack

    Stack Membro Participativo

    I've have a list of dicts:

    d = [{'n': 1, 'v': 'one'}, {'n': 2, 'v': 'two'}, ...]


    Update one dict's 'n' value, the rest of the list should reorder so that each 'n' is unique, and the associated 'v' values move along with their original 'n' values.

    Original:

    d = [
    {'n': 1, 'v': 'one'},
    {'n': 2, 'v': 'two'},
    {'n': 3, 'v': 'three'},
    {'n': 4, 'v': 'four'},
    {'n': 5, 'v': 'five'},
    ]


    If you do: d[1]['n'] = 3 Result should be:

    # [
    # {'n': 1, 'v': 'one'},
    # {'n': 2, 'v': 'three'},
    # {'n': 3, 'v': 'two'},
    # {'n': 4, 'v': 'four'},
    # {'n': 5, 'v': 'five'},
    # ]


    Here is my code:

    def update_n_value(d, index_to_update, new_n):
    # Step 1: Store old 'n' before any mutation
    old_n = d[index_to_update]['n']

    if old_n == new_n:
    # No change needed
    return sorted(d, key=lambda item: item['n'])

    # Step 2: Find the index of the item currently with new_n
    swap_index = next((i for i, item in enumerate(d) if item['n'] == new_n), None)

    if swap_index is None:
    raise ValueError(f"No item with 'n' = {new_n} to swap with.")

    # Step 3: Swap the 'n' values
    d[index_to_update]['n'] = new_n
    d[swap_index]['n'] = old_n

    # Step 4: Swap the corresponding 'v' values too
    d[index_to_update]['v'], d[swap_index]['v'] = d[swap_index]['v'], d[index_to_update]['v']

    # Step 5: Sort by 'n'
    d.sort(key=lambda item: item['n'])

    return d

    d = [
    {'n': 1, 'v': 'one'},
    {'n': 2, 'v': 'two'},
    {'n': 3, 'v': 'three'},
    {'n': 4, 'v': 'four'},
    {'n': 5, 'v': 'five'},
    ]

    # Move index 1 (n=2) → new_n = 3
    result = update_n_value(d.copy(), 1, 3)
    print(result)


    Getting incorrect output:

    [{'n': 1, 'v': 'one'}, {'n': 2, 'v': 'two'}, {'n': 3, 'v': 'three'}, {'n': 4, 'v': 'four'}, {'n': 5, 'v': 'five'}]

    Continue reading...

Compartilhe esta Página