**How are these two different. ** (1)
starting_dictionary = {
"a": 9,
"b": 8,
}
final_dictionary = {
"a": 9,
"b": 8,
"c": 7,
}
final_dictionary = starting_dictionary["c"] = 7
print(starting_dictionary)
print(final_dictionary)
(2)
starting_dictionary = {
"a": 9,
"b": 8,
}
final_dictionary = {
"a": 9,
"b": 8,
"c": 7,
}
starting_dictionary["c"] = 7
final_dictionary = starting_dictionary
print(starting_dictionary)
print(final_dictionary)
My main doubt is regarding the (1) code snippet, why does it not work like this : *starting_dictionary should add a new key-value pair of "c":7 *starting_dictionary should be assigned to final_dictionary *And now final_dictionary should have all of starting_dictionary with added key-value pair
In code snippet (1), the issue lies in the line:
This line of code doesn't achieve what you're intending. It actually assigns the value 7 to the key "c" in the starting_dictionary and then assigns the same value 7 to final_dictionary. It does not create a new dictionary with the added key-value pair.
Because:
starting_dictionary["c"] = 7: This modifies the starting_dictionary by adding the key "c" with the value 7.
final_dictionary = starting_dictionary["c"] = 7: It is equivalent to the below two steps-
starting_dictionary["c"] = 7: Modifies starting_dictionary. final_dictionary = 7: Assigns the value 7 to final_dictionary. So, after executing this line, both starting_dictionary and final_dictionary are pointing to the value 7, not to dictionaries.
On the other hand, code snippet (2) correctly adds the key-value pair to starting_dictionary and then assigns the reference of starting_dictionary to final_dictionary. Therefore, both dictionaries will have the same content after the execution of the code in snippet (2).