[Python] How do I preserve the order of keys when merging two Python dictionaries with...

Discussão em 'Python' iniciado por Stack, Novembro 29, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to merge two dictionaries in Python while not changing order, but also applying a custom rule for conflicts

    d1 = {"a": 1, "b": 2, "c": 3}

    d2 = {"b": 20, "d": 4}


    result = {}
    for k, v in d1.items():
    if k in d2:
    result[k] = [v, d2[k]]
    else:
    result[k] = v

    for k, v in d2.items():
    if k not in result:
    result[k] = v


    result I want

    {"a": 1, "b": [2, 20], "c": 3, "d": 4}

    Continue reading...

Compartilhe esta Página