My intended goal is to append a key value pair to a value in inside of a dictionary:
I have the following:
crucial = {'C': {'C': 0, 'B': 1}}
done = {}
for each in crucial:
for i in each:
done['D'] = 0
print(done)
print(crucial[i].append(done))
The output is:
Traceback (most recent call last):
File "C:\Users\User\Documents\Programming Full-Stack\Python\Exercise Files\02 Quick Start\conditionals.py", line 13, in <module>
print(crucial[i].append(done))
AttributeError: 'dict' object has no attribute 'append'
{'D': 0}
Expected output:
{'C': {'C': 0, 'B': 1, 'D':0}}
Therefore, can anyone provide me a guideline to append a key value pair to that value field in the outer dictionary?
Different approaches tried: So far I've tried converting the dictionary to a list declaring d as [], not with {}. I also tried putting .extend instead of .append. But in none of those cases I've got the result I wanted.
Thank you in advance
As the error states, dict
has no attribute append
. There is no append
method in the dictionary object. To assign a value to a particular key in a dictionary, it is simply:
d[key] = new_value
where new_value can be, if you wish: {'a':1}
If you are looking to update your dictionary with new data, you can use the update method.
d.update(new_stuff)
In your code, simply change your append, similar to the example I provided. I corrected it here:
crucial = {'C': {'C': 0, 'B': 1}}
done = {}
for each in crucial:
for i in each:
done['D'] = 0
print(done)
crucial[i].update(done)
print(crucial)
Python has a update function to add new items to dictionary
crucial .update({'D':'0'})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With