We can add / append new key-value pairs to a dictionary using update() function and [] operator. We can also append new values to existing values for a key or replace the values of existing keys using the same subscript operator and update() function.
To append an element to an existing dictionary, you have to use the dictionary name followed by square brackets with the key name and assign a value to it.
If you want to add a new key to the dictionary, then you can use the assignment operator with the dictionary key. This is pretty much the same as assigning a new value to the dictionary. Since Python dictionaries are mutable, when you use the assignment operator, you're simply adding new keys to the datastructure.
I am new to python and i am stuck while making a dictionary.. please help :)
This is what I am starting with :
dict = {}
dict['a']={'ra':7, 'dec':8}
dict['b']={'ra':3, 'dec':5}
Everything perfect till now. I get :
In [93]: dict
Out[93]: {'a': {'dec':8 , 'ra': 7}, 'b': {'dec': 5, 'ra': 3}}
But now, if I want to add more things to key 'a' and i do :
dict['a']={'dist':12}
Then it erases the previous information of 'a' and what i get now is :
In [93]: dict
Out[93]: {'a': {'dist':12}, 'b': {'dec': 5, 'ra': 3}}
What i get want to have is :
In [93]: dict
Out[93]: {'a': {'dec':8 , 'ra': 7, 'dist':12}, 'b': {'dec': 5, 'ra': 3}}
Can someone please help??
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