Home > database >  finding only one non zero value in a dictionary
finding only one non zero value in a dictionary

Time:10-27

I am looking for a way to get out of the dictionary one key and its value if it is not 0 and if all other values are 0. How is it possible to expand the below code and return 'is': 1?

test_dict = {'gfg': 0, 'is': 1, 'best': 0}
res = all(x == 0 for x in test_dict.values())
print("Does all keys have 0 value ? : "   str(res))

#Output
#Does all keys have 0 value ? : False

CodePudding user response:

key = None
value = None
for k, v in test_dict.items():
    if v != 0:
        if key is None:
            key = k
            value = v
        else:
            key = None
            value = None
            break
if key is not None:
    print(f"{key}: {value}")

CodePudding user response:

# Suggested implementation:
def get_single_non_zero_item(d):
    non_zeros = {k: v for k, v in d.items() if v != 0}
    is_single_non_zero = len(non_zeros) == 1
    assert is_single_non_zero, f"Error: got {len(non_zeros)} non zero items"
    return non_zeros


# Test implementation:
def run_get_single_non_zero_item(d):
    try:
        result = get_single_non_zero_item(d)    
        print(f"Got back a dict with {len(result)} items: {result}: ")
    except Exception as ex:
        print(ex)
    
dict_single_non_zero = {"first": 0, "second": 1, "third": 0}    
dict_all_zeros = {"first": 0, "second": 0, "third": 0}    
dict_all_non_zeros = {"first": 1, "second": 2, "third": 3}        

run_get_single_non_zero_item(dict_single_non_zero)  # Expect success
run_get_single_non_zero_item(dict_all_zeros) # Expect Failure
run_get_single_non_zero_item(dict_all_non_zeros) # Expect Failure

Results:

Got back a dict with 1 items: {'second': 1}:
Error: got 0 non zero items
Error: got 3 non zero items

CodePudding user response:

test_dict = {'gfg': 0, 'is': 1, 'best': 0}
res = False if all(x == 0 for x in test_dict.values()) else [{key:value} for key,value in test_dict.items() if test_dict[key]==1 ]
if res:
    print(res)
else:
    print("Does all keys have 0 value ? : "   str(res))

This will return a list. If you want only one value, you can print only the required index

[{'is': 1}]
  • Related