2021年6月27日 星期日

[ Python 常見問題 ] How do I merge two dictionaries in a single expression?

 Source From Here

Question
I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged (i.e. taking the union). The update() method would be what I need, if it returned its result instead of modifying a dictionary in-place:
  1. >>> x = {'a'1'b'2}  
  2. >>> y = {'b'10'c'11}  
  3. >>> z = x.update(y)  
  4. >>> print(z)  
  5. None  
  6. >>> x  
  7. {'a'1'b'10'c'11}  
How can I get that final merged dictionary in z, not x?

HowTo
For dictionaries x and yz becomes a shallowly merged dictionary with values from y replacing those from x.

In Python 3.9.0 or greater (released 17 October 2020):
PEP-584discussed here, was implemented and provides the simplest method:
  1. >>> x = {'a'1'b'2}  
  2. >>> y = {'b:'10'c'11}  
  3. >>> z = x | y  
  4. >>> z  
  5. {'a'1'b'2'b:'10'c'11}  
In Python 3.5 or greater:
  1. >>> x = {'a'1'b'2}  
  2. >>> y = {'b:'10'c'11}  
  3. >>> z = {**x, **y}  
  4. >>> z  
  5. {'a'1'b'2'b:'10'c'11}  
In Python 2, (or 3.4 or lower) write a function:
  1. def merge_two_dicts(x, y):  
  2.     z = x.copy()   # start with x's keys and values  
  3.     z.update(y)    # modifies z with y's keys and values & returns None  
  4.     return z  
  5.   
  6. x = {'a'1'b'2}  
  7. y = {'b:'10'c'11}  
  8. z = merge_two_dicts(x, y)  


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...