Home > database >  How do I create a new dictionary with the max key/value pairs from 4 other dictionarys?
How do I create a new dictionary with the max key/value pairs from 4 other dictionarys?

Time:07-23

I have four dictionaries with dates as the keys and some file ids:

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

I want to create a new dictionary with the maximum key/value pairs from each of them, resulting in:

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

The closest I've gotten so far is max(dict1.items()) but this returns ('20220509', 'def'), which then I can't figure out a way to manipulate this back into dictionary form. Any ideas on a pythonic way to accomlish this?

CodePudding user response:

The dict() function can take a list of tuples (key, value), and reform them into a dictionary; so you can make a list of tuples where each item is the max value of each dictionary

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

Output:

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

CodePudding user response:

newdict = {}
for d in [dict1, dict2, dict3, dict4]:
    newdict[max(d)] = d[max(d)]

I believe you want to use the max value as the key for each dictionary, and grab the value and add to the newdict.

  • Related