Dictionary merge. The input uses a string to represent two dictionaries, and the combined dictionary is output. The keys of the dictionary are represented by a letter or number. Note: 1 and '1' are different keywords!
Input format:
Enter the first dictionary string in the first line Enter the second dictionary string in the second line
Output format:
The combined dictionary is output in one line, and the output is in lexicographic order. The ASCII value of "1" is 49, which is greater than 1. When sorting, 1 is first, "1" is next, and the others are the same.
Input example 1:
Here is a set of inputs. E.g:
{1:3,2:5}
{1:5,3:7}
Sample output 1:
The corresponding output is given here. E.g:
{1:8,2:5,3:7}
Input example 2:
Here is a set of inputs. E.g:
{"1":3,1:4}
{"a":5,"1":6}
Sample output 2:
The corresponding output is given here. E.g:
{1:4,"1":9,"a":5}
第一版(代码死板,不建议参考,见第二版)
# Dictionary merge # Author: cnRick # Time: 2020-4-10 dict1 = eval (the INPUT ()) dict2 = eval(input()) keys1 = dict1.keys() keys2 = dict2.keys() minLenFlag = 1 if len(dict1) > len(dict2) else 0 if minLenFlag == 0: for i in keys1: if i in dict2: dict2[i] = dict2[i] + dict1[i] else: dict2[i] = dict1[i] keys = list(dict2.keys()) keys.sort(key = lambda x: ord(x) if type(x)==str else x) cnt = 0 print("{",end="") for i in keys: if type(i) == int: print("{:d}:{:d}".format(i,dict2[i]),end="") cnt += 1 elif type(i) == str: print('"{:s}":{:d}'.format(i,dict2[i]),end="") cnt += 1 if cnt != len(dict2): print(",",end="") print("}",end="") else: for i in keys2: if i in dict1: dict1[i] = dict1[i] + dict2[i] else: dict1[i] = dict2[i] keys = list(dict1.keys()) keys.sort(key = lambda x: ord(x) if type(x)==str else x) cnt = 0 print("{",end="") for i in keys: if type(i) == int: print("{:d}:{:d}".format(i,dict1[i]),end="") cnt += 1 elif type(i) == str: print('"{:s}":{:d}'.format(i,dict1[i]),end="") cnt += 1 if cnt != len(dict1): print(",",end="") print("}",end="")
second edition
1 # 字典合并-简化版 2 # Author: cnRick 3 # Time : 2020-4-10 4 dict1 = eval(input()) 5 dict2 = eval(input()) 6 for key in dict2.keys(): 7 dict1[key] = dict1.get(key,0) + dict2[key] 8 9 items_list = list(dict1.items()) 10 items_list.sort(key=lambda item:ord(item[0]) if type(item[0]) == str else item[0]) 11 print(str(dict(items_list)).replace(" ","").replace("'",'"'))
Ideas for reference: https://blog.csdn.net/qq_43479432/article/details/105009411