@@ -75,6 +75,63 @@ d.update((["f", 0],), f = 6)
7575expected = {"a" : 1 , "b" : 2 , "c" : 3 , "d" : 4 , "e" : 5 , "f" : 6 }
7676assert_eq (d , expected )
7777
78+ # dict union operator |
79+
80+ empty_dict = dict ()
81+ dict_with_a_b = dict (a = 1 , b = [1 , 2 ])
82+ dict_with_b = dict (b = [1 , 2 ])
83+ dict_with_other_b = dict (b = [3 , 4 ])
84+
85+ assert_eq (empty_dict | dict_with_a_b , dict_with_a_b )
86+ # Verify iteration order.
87+ assert_eq ((empty_dict | dict_with_a_b ).items (), dict_with_a_b .items ())
88+ assert_eq (dict_with_a_b | empty_dict , dict_with_a_b )
89+ assert_eq ((dict_with_a_b | empty_dict ).items (), dict_with_a_b .items ())
90+ assert_eq (dict_with_b | dict_with_a_b , dict_with_a_b )
91+ assert_eq ((dict_with_b | dict_with_a_b ).items (), dict (b = [1 , 2 ], a = 1 ).items ())
92+ assert_eq (dict_with_a_b | dict_with_b , dict_with_a_b )
93+ assert_eq ((dict_with_a_b | dict_with_b ).items (), dict_with_a_b .items ())
94+ assert_eq (dict_with_b | dict_with_other_b , dict_with_other_b )
95+ assert_eq ((dict_with_b | dict_with_other_b ).items (), dict_with_other_b .items ())
96+ assert_eq (dict_with_other_b | dict_with_b , dict_with_b )
97+ assert_eq ((dict_with_other_b | dict_with_b ).items (), dict_with_b .items ())
98+
99+ assert_eq (empty_dict , dict ())
100+ assert_eq (dict_with_b , dict (b = [1 ,2 ]))
101+
102+ assert_fails (lambda : dict () | [], "unsupported binary operation" )
103+
104+ # dict union assignment operator |=
105+
106+ def test_dict_union_assignment ():
107+ empty_dict = dict ()
108+ empty_dict |= {"a" : 1 }
109+ empty_dict |= {"b" : 2 }
110+ empty_dict |= {"c" : "3" , 7 : 4 }
111+ empty_dict |= {"b" : "5" , "e" : 6 }
112+ expected_1 = {"a" : 1 , "b" : "5" , "c" : "3" , 7 : 4 , "e" : 6 }
113+ assert_eq (empty_dict , expected_1 )
114+ assert_eq (empty_dict .items (), expected_1 .items ())
115+
116+ dict_a = {8 : 1 , "b" : 2 }
117+ dict_b = {"b" : 1 , "c" : 6 }
118+ dict_c = {"d" : 7 }
119+ dict_tuple = {(5 , "a" ): ("c" , 8 )}
120+ dict_a |= dict_b
121+ dict_c |= dict_a
122+ dict_c |= dict_tuple
123+ expected_2 = {"d" : 7 , 8 : 1 , "b" : 1 , "c" : 6 , (5 , "a" ): ("c" , 8 )}
124+ assert_eq (dict_c , expected_2 )
125+ assert_eq (dict_c .items (), expected_2 .items ())
126+ assert_eq (dict_b , {"b" : 1 , "c" : 6 })
127+
128+ test_dict_union_assignment ()
129+
130+ def dict_union_assignment_type_mismatch ():
131+ some_dict = dict ()
132+ some_dict |= []
133+
134+ assert_fails (dict_union_assignment_type_mismatch , "unsupported binary operation" )
78135
79136# creation with repeated keys
80137
0 commit comments