【问题标题】:returns a new dictionary which has all key value pairs from three dictionaries [duplicate]返回一个新字典,其中包含来自三个字典的所有键值对 [重复]
【发布时间】:2020-05-10 23:10:56
【问题描述】:
new_dict={}
d1={'name1':'Jaison','name3':'Eldose','name2':'Manu'}
d2={'age1':29,'age2':26,'age3':28}
d3={'job1':'NJ','job2':'SE','job3':'SE'}
def Combine_dictionaries(*args):
    for arg in args:
        for i,j in arg.items():
            print(i,j)
            new_dict[i]=[j]
    return new_dict  

print(Combine_dictionaries(d1,d2,d3))
print(new_dict.items())

输出:

dict_items([('name1', ['Jaison']), ('name3', ['Eldose']), ('name2', ['Manu']), ('age1', [29]), ('age2', [26]), ('age3', [28]), ('job1', ['NJ']), ('job2', ['SE']), ('job3', ['SE'])])

问题: 有什么改进输出的建议吗?

【问题讨论】:

标签: python dictionary


【解决方案1】:

我个人认为这可能不应该是一本字典。我很可能不会索引到字典中寻找“name1”。我会列出这个列表,也许是这样。

names = ['Jaison', 'Eldose', 'Manu'] # then names[0] = 'Jaison'
ages = [29, 26, 28]
jobs = ['NJ', 'SE', 'SE']

为了组合它们,我们可以有一个字典列表的元组列表。

people_list = [(names[i], ages[i], jobs[i]) for i in range(len(names))]
# [('Jaison', 29, 'NJ'), ('Eldose', 26, 'SE'), ('Manu', 28, 'SE')]
people_dict = [{'name':names[i], 'age':ages[i], 'job':jobs[i]} for i in range(len(names))]
#[{'name': 'Jaison', 'age': 29, 'job': 'NJ'}, {'name': 'Eldose', 'age': 26, 'job': 'SE'}, {'name': 'Manu', 'age': 28, 'job': 'SE'}]

不过只是一个建议。希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 2022-08-21
    • 1970-01-01
    • 2022-07-21
    相关资源
    最近更新 更多