Home > Software engineering >  How to find the dict which has more number of filled values?
How to find the dict which has more number of filled values?

Time:04-20

I have two Dicts

a = {'A':'',
     'B':'234923',
     'C': 'adkasd',
     'D':'kajskdad'}

b = {'A':'',
     'B':'dfdsf',
     'C': 'adkasd',
     'D':''}

How to return the Dict which has more filed values ( non '' values) out of these 2 Dicts?

I tired this Function:

def getLargerData(dict1, dict2):
    countA = len([i for i in dict1.values() if i != ''])
    countB = len([i for i in dict2.values() if i != ''])
    if countA > countB:
        return dict1
    else:
        return dict2

Output:

{'A':'',
 'B':'234923',
 'C': 'adkasd',
 'D':'kajskdad'}

is there any way I can optimize more or alternate solutions for this?

CodePudding user response:

You can simply check for the count of all values in each dictionary. Thanks to @deceze for the comment to get the oneliner sum of each value of dict.

def getLargerData(dict1, dict2):
    countA = sum(1 for i in dict1.values() if i)
    countB = sum(1 for j in dict2.values() if j)
    
    return dict1 if countA > countB else dict2

getLargerData(a,b)

Output:

{'A': '', 'B': '234923', 'C': 'adkasd', 'D': 'kajskdad'}

CodePudding user response:

try this, its a bit "optimized"

def getLargerData(dict1, dict2):
    '''returns True if dict1 is larger than dict2 otherwise returns false'''
    return len([i for i in dict1.values() if i != '']) > len([i for i in dict2.values() if i != ''])
  • Related