[python]Python 字典(Dictionary) update()方法

  • 2020 年 2 月 24 日
  • 筆記

update() 函數把字典dict2的鍵/值對更新到dict里。如果後面的鍵有重複的會覆蓋前面的 語法 dict.update(dict2)

dict = {'Name': 'Zara', 'Age': 7} dict2 = {'Sex': 'female','Name':'zhangsan'} dict.update(dict2) print "Value : %s" % dict

結果:

root@tao:/home/tao# python  Python 2.7.17 (default, Nov  7 2019, 10:07:09)  [GCC 9.2.1 20191008] on linux2  Type "help", "copyright", "credits" or "license" for more information.  >>> dict = {'Name': 'Zara', 'Age': 7}  >>> dict2 = {'Sex': 'female','Name':'zhangsan'}  >>> dict.update(dict2)  >>> print "Value : %s" %  dict  Value : {'Age': 7, 'Name': 'zhangsan', 'Sex': 'female'}  >>> 

php中類似的語法是array_merge

array_merge() 將一個或多個數組的單元合併起來,一個數組中的值附加在前一個數組的後面。返回作為結果的數組。 如果輸入的數組中有相同的字符串鍵名,則該鍵名後面的值將覆蓋前一個值。然而,如果數組包含數字鍵名,後面的值將不會覆蓋原來的值,而是附加到後面。 如果只給了一個數組並且該數組是數字索引的,則鍵名會以連續方式重新索引。

<?php  $array1 = array("color" => "red", 2, 4);  $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);  $result = array_merge($array1, $array2);  print_r($result);  ?>  以上例程會輸出:    Array  (      [color] => green      [0] => 2      [1] => 4      [2] => a      [3] => b      [shape] => trapezoid      [4] => 4  )