字典合并。输入用字符串表示两个字典,输出合并后的字典,字典的键用一个字母或数字表示。注意:1和‘1’是不同的关键字!
输入格式:
在第一行中输入第一个字典字符串 在第二行中输入第二个字典字符串
输出格式:
在一行中输出合并的字典,输出按字典序。
输入样例:
在这里给出一组输入。例如:
{1:3,2:5}
{1:5,3:7}
输出样例:
在这里给出相应的输出。例如:
{1:8,2:5,3:7}
这道题刚开始我感觉很简单,但是到后面一直不通过的原因是输出有问题。。
贴代码了,道理都懂。。。
a = dict(eval(input()))
b = dict(eval(input()))
c = {}
for i in a.keys():
for j in b.keys():
if i == j:
c[i] = a.get(i) + b.get(j)
if i not in c.keys():
c[i] = a.get(i)
if j not in c.keys():
c[j] = b.get(j)
c1 = {}
c2 = {}
for key in c.keys():
if type(key) == str:
c1[key] = c.get(key)
elif type(key) == int:
c2[key] = c.get(key)
c11 = sorted(c1.keys())
c22 = sorted(c2.keys())
ans1 = {} #str
ans2 = {} #int
ans3 = {}
for i in c11:
ans1[i] = c1.get(i)
for i in c22:
ans2[i] = c2.get(i)
# ans3.update(ans2)
# ans3.update(ans1)
num = 0
num1 = 0
print("{", end='')
if len(ans2) != 0:
for k, v in ans2.items():
if len(ans1) == 0 and num1 == len(ans2) - 1:
print("{}:{}".format(k, v), end='')
else:
print("{}:{},".format(k, v), end='')
num1 = num1 + 1
if len(ans1) != 0:
for k, v in ans1.items():
if num == len(ans1) - 1:
print(("\""+"%c"+"\""+":"+"%d") % (k, v), end='')
else:
print(("\"" + "%c" + "\"" + ":" + "%d,") % (k, v), end='')
num = num + 1
print("}", end='')