| und |= in Python

avatar

Also wirklich. Was ist das denn für eine kryptische Überschrift??? Jetzt liest doch niemand mehr diesen Beitrag :)
Mit der Pythonversion 3.9 wurden zwei Operatoren für Dictionaries eingeführt, um so auch etwas schreibarbeit zu sparen.
Einmal der Mergeoperator | um zwei Dictionaries miteinander zu verschmelzen und der Updateoperator |= um ein Dictionary um ein anderes zu aktualisieren. Doch Vorsicht! Die Reihenfolge der Dictionaires sind wichtig, ansonsten habt ihr unerwünschte Resultate. Links des Operators immer das Dictionary schreiben welches um das Rechte aktualisiert werden soll.

Sehen wir uns mal ein Beispiel dazu an

def merge_dicts(dict1,dict2):
    # merge the second dictionary in the first dictionary
    # if same keys exist in second dictionary the value of this key will be overwritten in the first dictionary
    # if keys from the second dictionary don't exist the key-, valuepair will be added in the first dictionary
    # Merge creates a new dictionary
    return dict1 | dict2

def update_dicts(dict1,dict2):
    # update works the same like merge except it creates NOT a new dictionary. It overwrites the dict1 entries
    dict1 |= dict2
    return dict1

if __name__ == '__main__':
    # create two dictionaries
    dict1 = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
    dict2 = {5: 'e', 6: 'f', 2: 'g', 4: 'h'}

    # merge dict1 and dict2
    print(merge_dicts(dict1,dict2))

    # update dict1 with dict2
    print(update_dicts(dict1,dict2))



0
0
0.000
0 comments