如何在python中添加字典数组?

时间:2019-01-26 20:42:54

标签: python dictionary

first_obj= [{"name":"sat","age":20}]
second_obj = [{"country":'India'}]

如何在python中添加字典数组?

third_obj = [{"name":'sat',"age":20,"country":'India'}]

2 个答案:

答案 0 :(得分:1)

first_obj= [{"name":"sat","age":20}]
second_obj = [{"country":'India'}]

third_obj = [{**first_obj[0], **second_obj[0]}]
print(third_obj)

输出

[{'name': 'sat', 'country': 'India', 'age': 20}]

答案 1 :(得分:0)

假设两个对象的长度始终相同,则可以迭代两个列表并合并字典:

third_obj = []
for a, b in zip(first_obj, second_obj):
   combined_dict = dict(a.items() + b.items()) # merge dictionaries
   third_obj.append(combined_dict)