­

[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  )