python怎麼將字典key相同的value值, 合併
python怎麼將字典key相同的value值, 合併
python怎麼將字典key相同的value值, 以逗號隔開,整為一行數據
源數據:
test_dict1 = {text: 50.00€ Rabatt für Bestellungen über 10.00€, strong_off: 50.00€, html_text: <font color=#D53333>50.00€ Rabatt</font> für Bestellungen über 10.00€}
test_dict2 = {text: 80.00€ Rabatt für Bestellungen über 20.00€, strong_off: 80.00€, html_text: <font color=#D53333>80.00€ Rabatt</font> für Bestellungen über 20.00€}
輸出結果如下:
{text: 50.00€ Rabatt für Bestellungen über 10.00€, 80.00€ Rabatt für Bestellungen über 20.00€, strong_off: 50.00€, 80.00€, html_text: <font color=#D53333>50.00€ Rabatt</font> für Bestellungen über 10.00€, <font color=#D53333>80.00€ Rabatt</font> für Bestellungen über 20.00€}
用一到兩行代碼實現上面的要求:
下面是三個方案:最好的是第一個,最差的是第三個
from timeit import timeit
def test110(): all_test_dict = {key: ", ".join([test_dict1[key], test_dict2[key]]) for key in test_dict1 if key in test_dict2}# print(all_test_dict)
def test112(): all_test_dict = {} for key in test_dict1.keys() & test_dict2.keys():all_test_dict[key] = "{},{}".format(test_dict1[key], test_dict2[key])
# print(all_test_dict)def test113(): for key in test_dict1:test_dict1[key] += , + test_dict2.get(key)
# print(test_dict1)print(timeit(stmt=test110, number=1000))print(timeit(stmt=test112, number=1000))print(timeit(stmt=test113, number=1000))輸出時間:
0.0028012706343090144
0.004388619569021927
0.00776079210373197
推薦閱讀: