【问题标题】:How do I create a new dictionary with the max key/value pairs from 4 other dictionarys?如何使用来自其他 4 个字典的最大键/值对创建一个新字典?
【发布时间】:2022-07-23 01:06:58
【问题描述】:

我有四个字典,其中日期作为键和一些文件 ID:

dict1 = {'20220101':'abc','20220509':'def'}
dict2 = {'20220705':'ghi','20220810':'jkl'}
dict3 = {'20221015':'mno','20221014':'pqr'}
dict4 = {'20221208':'stu','20221231':'vwx'}

我想创建一个新字典,其中每个字典包含最大的键/值对,结果是:

newdict = {'20220509':'def','20220810':'jkl','20221015':'mno','20221231':'vwx'}

到目前为止,我得到的最接近的是 max(dict1.items()) 但这会返回 ('20220509', 'def'),然后我想不出办法将其重新转换为字典形式。有什么关于 pythonic 方式的想法吗?

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    dict() 函数可以获取一个元组列表(键、值),并将它们改造成字典;所以你可以制作一个元组列表,其中每个项目是每个字典的最大值

    newdict = dict([max(x.items()) for x in [dict1, dict2, dict3, dict4]])
    print(final)
    

    输出:

    {'20220509': 'def', '20220810': 'jkl', '20221015': 'mno', '20221231': 'vwx'}
    

    【讨论】:

    • 本来打算在我自己的答案中添加一个特定于问题的示例,但现在没有意义 :)
    【解决方案2】:
    newdict = {}
    for d in [dict1, dict2, dict3, dict4]:
        newdict[max(d)] = d[max(d)]
    

    我相信你想使用最大值作为每个字典的键,并获取值并添加到新字典中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 2019-02-23
      • 1970-01-01
      • 2018-04-30
      • 1970-01-01
      相关资源
      最近更新 更多