Home > Software design >  AttributeError: 'NoneType' object has no attribute 'keys' (Python)
AttributeError: 'NoneType' object has no attribute 'keys' (Python)

Time:01-22

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}

CodePudding user response:

I found the answer) since dictionaries are mutable are should've used d.update() instead of d = d.update(). And one else mistake, but not according to the question topic

CodePudding user response:

It looks like you want to accumulate values from the other two dicts into the first one, or just transfer values if not already present.

This is the code you want:

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
            else:
                d[k] = v
        
    print(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)

Output as requested

CodePudding user response:

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}
  • Related