题目:
输入两个字典列表,其中字典的键全为字符串,值全为整数。将其按照字典内键的顺序,将对应的键拼接,值相加,得到新的字典。
示例:
# 输入
a_list = [{'a': 3}, {'b': 1}, {'c': 5}]
b_list = [{'a': 3}, {'f': 2}, {'d': 4}]
# 输出
[{'aa': 6}, {'bd': 5}, {'cf': 7}]
代码如下:
a_list = [{'a': 3}, {'b': 1}, {'c': 5}]
b_list = [{'a': 3}, {'f': 2}, {'d': 4}]
a_list_sort = [{i[0]: i[1]} for i in sorted({j: i[j] for i in a_list for j in i.keys()}.items(), key=lambda a: a[0])]
b_list_sort = [{i[0]: i[1]} for i in sorted({j: i[j] for i in b_list for j in i.keys()}.items(), key=lambda a: a[0])]
a_list_sort_key = []
a_list_sort_value = []
b_list_sort_key = []
b_list_sort_value = []
for i in range(len(a_list_sort)):
for key, value in a_list_sort[i].items():
a_list_sort_key.append(key)
a_list_sort_value.append(value)
for i in range(len(b_list_sort)):
for key, value in b_list_sort[i].items():
b_list_sort_key.append(key)
b_list_sort_value.append(value)
result_list = []
for j in range(len(a_list_sort_key)):
result_dict = {}
new_key = a_list_sort_key[j] + b_list_sort_key[j]
new_value = a_list_sort_value[j] + b_list_sort_value[j]
result_dict[new_key] = new_value
result_list.append(result_dict)
print(result_list)