Search code examples
pythonfunctiondictionarykey

AttributeError: 'NoneType' object has no attribute 'keys' (Python)


I'm writing a function that takes a number of dictionaries (keys - letters, values - numbers) and combines them into one dictionary. Dict values should be summarized in case of identical keys, but alwayw recieve the error for the line with " if k in d.keys():" AttributeError: 'NoneType' object has no attribute 'keys'

def combine(*args):
    d = args[0]

    for dct in args[1:]:
        for k, v in dct.items():
            if k in d.keys():
                d[k] = d[k] + v
        d = d.update(dct)
    print(d)


dict_1 = {'a': 100, 'b': 200}
dict_2 = {'a': 200, 'c': 300}
dict_3 = {'a': 300, 'd': 100}

combine_dicts(dict_1, dict_2, dict_3)

result should be {'a': 600, 'b': 200, 'c': 300, 'd': 100}


Solution

  • What's wrong with your code.
    1. d = d.update(dct) will override exist data and and that's where you are getting AttributeError: because a none is returned. 2. You are calling a wrong function, your function is called combine and you are calling combine_dicts.

    This is one of the appropriate approaches you can take you can taking using defaultdict from collections.

    from collections import defaultdict
    
    def combine(*args):
        d = defaultdict(int)
        for dct in args:
            for key, value in dct.items():
                d[key] += value
        print(dict(d))
    
    dict_1 = {'a': 100, 'b': 200}
    dict_2 = {'a': 200, 'c': 300}
    dict_3 = {'a': 300, 'd': 100}
    
    combine(dict_1, dict_2, dict_3)
    

    {'a': 600, 'b': 200, 'c': 300, 'd': 100}