'How to find the dict which has more number of filled values?
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?
Solution 1:[1]
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'}
Solution 2:[2]
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 != ''])
this is how it works:
def getLargerData(dict1,dict2): Defines the function
return returns IF:
len(the length of[i for i in dict1.values() if i != '']returns all the values in dict1 if it isn't none
>returns if that is greater thanlen(the length of[i for i in dict2.values() if i != '']returns all the values in dict2 if it isn't none
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
