Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

SOLVED: String by value; Dictionary by reference?


I'm coming from C, learning Python. In Python (3.5.2), it seems that assignment of one data type to another of the same type is sometimes done by value and sometimes by reference.

For example, strings are assigned by value:

>>> str1 = "hello"
>>> str2 = str1
>>> print(str1, str2)
hello hello
>>> str2 = "goodbye"
>>> print(str1, str2)
hello goodbye

This is the behavior I expect. However, it works differently with dictionaries:

>>> dict1 = {'key1':'val1', 'key2':'val2'}
>>> dict2 = dict1
>>> print(dict1, dict2)
{'key2': 'val2', 'key1': 'val1'} {'key2': 'val2', 'key1': 'val1'}
>>> dict2['key1'] = 'newval'
>>> print(dict1, dict2)
{'key2': 'val2', 'key1': 'newval'} {'key2': 'val2', 'key1': 'newval'}

Notice that both dict1 and dict2 were changed. Similarly, if I add a key/value pair to either of the dictionaries it will appear in both. Argh!

(sorry, that was my C-background speaking) :)

How am I to know which behavior to expect for any given variable type? Is there a method to this madness or will I simply need to remember arbitrary rules?

P.S. I realize I can get my expected behavior by using dict2 = dict(dict1).

The "possible duplicate" contains good info on how to do it, but I'm interested in why I have to. The answers to this question are already very helpful!

Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered

This post first appeared on Stack Solved, please read the originial post: here

Share the post

SOLVED: String by value; Dictionary by reference?


Subscribe to Stack Solved

Get updates delivered right to your inbox!

Thank you for your subscription