How do I extend dictionary?

Asked 2 years ago, Updated 2 years ago, 66 views

In the list, you could have just attached it as an extension, but what should I do to extend the dictionary?

I want to avoid "for loop."

a = { "a" : 1, "b" : 2 }
b = { "c" : 3, "d" : 4 }

'''
I can't do that
a.extend(b) # a = { "a" : 1, "b" : 2, "c" : 3, "d" : 4}
'''

dictionary python

2022-09-21 18:54

1 Answers

dict.update([other]) updates existing dict from key-value in other

If another key overlaps with an existing key, change the value corresponding to the key, and

If there is a key in other that is not in the existing key, add a key-value

a = { "a" : 1, "b" : 2 }
b = { "c" : 3, "d" : 4 }
c = { "a" : 5, "b" : 6 }

a.update(b)
print(a)

a.update(c)
print(a)

Output:

{'a': 1, 'c': 3, 'd': 4, 'b': 2}
{'b': 6, 'a': 5, 'c': 3, 'd': 4}


2022-09-21 18:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.