0
def modify(a_dict):
    alt_dict = a_dict.copy()
    alt_dict['s'] = 2
    a_dict = alt_dict

a_dictionary = {}
a_dictionary['f'] = 5

modify(a_dictionary)
print(a_dictionary)

The expected result is that a_dictionary will now also containt the key 's'. I know lists and dictionaries are passed by reference as mutables, but is there a way to update the reference within a function as I'm trying to do above?.. Or is there a better way?..

To clarify, I do indeed need to make a copy, because the changes I make in inside my actual function in code I might discard if an exception happens.

3 Answers 3

2

Assigning a new object to the local variable doesn't help you here. But as dictionaries are mutable, you can clear and update the original dictionary given the new data:

def modify(a_dict):
    alt_dict = a_dict.copy()
    alt_dict['s'] = 2
    a_dict.clear()
    a_dict.update(alt_dict)
Sign up to request clarification or add additional context in comments.

Comments

0

You can do:

def modify(a_dict):
    alt_dict = a_dict.copy()
    alt_dict['s'] = 2
    # do lots of stuff

    # make sure all changes are "backported"
    a_dict.update(alt_dict)

Comments

0

How about returning the modified copy?

def modify(a_dict):
    alt_dict = a_dict.copy()
    alt_dict['s'] = 2
    return alt_dict

a_dictionary = {}
a_dictionary['f'] = 5

a_dictionary = modify(a_dictionary)
print(a_dictionary)

2 Comments

Unfortunately I'm returning other things in my actual code, that's why I needed to do it by reference, but this is a good suggestion
@JackAvante A function in Python can return an arbitrary number of objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.