Home > other >  A python interview question, the right answer
A python interview question, the right answer

Time:11-19

Implement the following function in python (30 minutes) :
Merge dict
Def merge_dict (source_dict update_dict) - & gt; Dict
Example: a={' a ':' a ', 'b', 'b'}
B={' b ', 'c', 'c' : {' d ':' d '}}
Result=merge_dict (a, b)//result={' a ':' a ', 'b', 'c', 'c' : {' d ':' d '}}
Note:
The processing of with nested
Need to check all kinds of abnormal, conflict, the specific values, and throw exception right
The code to compile and execute

CodePudding user response:

 def merge_dict (source_dict: dict, update_dict: dict) : 
For the key in source_dict. Keys () :
If the key not in update_dict. Keys () :
[key] update_dict [key]=source_dict

Print (update_dict)

If __name__=="__main__ ':
A={' a ':' a ', 'b', 'b'}
B={' b ', 'c', 'c' : {' d ':' d '}}
Merge_dict (a, b)

So!!!! In addition, there are still some shortage, is unusual, special value and exactly what is, I don't know, to forgive a small white I algorithm can't!

CodePudding user response:

Through two dictionaries, if there is a new value, the new dictionary will replace the old with the new values the values in the dictionary

CodePudding user response:

B={' b ', 'c', 'c' : {' d ':' d '}}
A={' a ':' a ', 'b', 'b'}
For the item, the value in b.i tems () :
A [items]=value

Print (b)
Print (a)

CodePudding user response:

 a.u pdate (b) 

CodePudding user response:

Example: a={' a ':' a ', 'b', 'b'}
B={' b ', 'c', 'c' : {' d ':' d '}}
Result=merge_dict (a, b)//result={' a ':' a ', 'b', 'c', 'c' : {' d ':' d '}}


According to this result, you can see, the key value for that come after shall prevail, that is to say, if there is a repeated direct cover,
If you want to achieve this, a word is enough, a.u pdate (b)

CodePudding user response:

Never thought someone wrote, in front of the this reply to audit, generally 0 to 20 min, is actually quite a few minutes can't see the previous

CodePudding user response:

It doesn't matter, thank you very much!
  • Related