Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append Key and Value to a Key Value pair Dictionary Python

Tags:

python

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

like image 936
NellMartin Avatar asked Mar 06 '16 17:03

NellMartin


2 Answers

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)
like image 67
idjaw Avatar answered Sep 27 '22 23:09

idjaw


Python has a update function to add new items to dictionary

crucial .update({'D':'0'})
like image 45
Henin RK Avatar answered Sep 28 '22 00:09

Henin RK