In python, there are multiple ways to add keys or values to dictionary.
You can use assignment operator to add key to dictionary.
# Updates if ‘x’ exists, else adds ‘x’
dic[‘x’]=1
dic[‘x’]=1
There are other ways to add to dictionay as well in python.
dic.update({‘x’:1})
# OR
dic.update(dict(x=1))
# OR
dic.update(x=1)
# OR
dic.update(dict(x=1))
# OR
dic.update(x=1)
Example:
1 2 3 4 5 6 |
d = {'x':1,'y':2,'z':3} print("Before:",d) d['p']='24' print("After:",d) |
Output:
Before: {‘x’: 1, ‘y’: 2, ‘z’: 3}
After: {‘x’: 1, ‘y’: 2, ‘z’: 3, ‘p’: ’24’}
After: {‘x’: 1, ‘y’: 2, ‘z’: 3, ‘p’: ’24’}
Further reading:
Add multiple keys to dictionary
If you want to add multiple keys in one time, you can use update method.
1 2 3 4 5 6 7 |
d = {'x':1,'y':2,'z':3} print("Before:",d) p = {'a':4,'b':5} d.update(p) print("After:",d) |
Output:
Before: {‘x’: 1, ‘y’: 2, ‘z’: 3}
After: {‘x’: 1, ‘y’: 2, ‘z’: 3, ‘a’: 4, ‘b’: 5}
After: {‘x’: 1, ‘y’: 2, ‘z’: 3, ‘a’: 4, ‘b’: 5}
That’s all about Python add to Dictionary.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.