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

前端之家收集整理的这篇文章主要介绍了[python]Python 字典(Dictionary) update()方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

update() 函数把字典dict2的键/值对更新到dict里。如果后面的键有重复的会覆盖前面的
语法
dict.update(dict2)

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

结果:

  1. root@tao:/home/tao# python
  2. Python 2.7.17 (default,Nov 7 2019,10:07:09)
  3. [GCC 9.2.1 20191008] on linux2
  4. Type "help",1)">copyrightcredits" or license" for more information.
  5. >>> dict = {'Name': Zara',1)">Age7}
  6. >>> dict2 = {Sexfemale':zhangsan'}
  7. >>> dict.update(dict2)
  8. >>> print Value : %s" % dict
  9. Value : {7,1)">}
  10. >>>

 

PHP中类似的语法是array_merge

array_merge() 将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。
如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。
如果只给了一个数组并且该数组是数字索引的,则键名会以连续方式重新索引。

  1. <?PHP
  2. $array1 = array(color" => red2,1)">4);
  3. $array2 = array(abgreenshapetrapezoid);
  4. $result = array_merge($array1,$array2);
  5. print_r($result);
  6. ?>
  7. 以上例程会输出
  8. Array
  9. (
  10. [color] => green
  11. [0] => 2
  12. [1] => 2] => a
  13. [3] => b
  14. [shape] => trapezoid
  15. [4] =>
  16. )

 

猜你在找的Python相关文章