[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

結果:

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
)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM