简体   繁体   中英

Swap dictionary values

Complete the given method called solve which takes as parameter a dictionary A.

A has some keys, but the values of the keys 'x' and 'y' have been mistakenly swapped. You have to put them back in their original positions, And return the dictionary.

Example Input: {'a': 1, 'b': 200, 'x': 2, 'y': 7}

Output: {'a': 1, 'b': 200, 'x': 7, 'y': 2}

def swap(a,b):
    temp=a
    a=b
    b=temp
def solve(A):
    print(swap(A['x'],A['y'])

i know i did it wrong, but cant understand it!

This has do with mutability in Python: whether a given object in memory can or can't be changed. You're providing the function with variables that point to integer objects, and these are immutable.

You can verify this yourself in the Python interpreter.

>>> A = {'a': 1, 'b': 200, 'x': 2, 'y': 7}
>>> x = A['x']
>>> x
2
>>> id(A['x'])
4402888976
>>> id(x)
4402888976
>>> x = 5
>>> id(A['x'])
4402888976
>>> id(x)
4402889072
>>> A
{'a': 1, 'b': 200, 'x': 2, 'y': 7}
>>> x
5

As you can see in this example, x initially has the same identity as A['x'] (they point to the same object in memory that holds the integer value 2 ). But when we assign x a new value, since integers are immutable, Python doesn't change the value where 2 is stored in memory; instead, it allocates another space in memory where it stores the integer value 5 and points x to it. So x points to another integer object in memory while A['x'] keeps pointing to the initial value it was assigned. The same thing is happening with your function.

Now, dictionaries a mutable objects in Python, so if you pass the dictionary instead of two integers, you can manipulate the dictionary within the function and your changes will remain after the function exits.

>>> A = {'a': 1, 'b': 200, 'x': 2, 'y': 7}
>>> def solve(d):
...     d['x'], d['y'] = d['y'], d['x']
...
>>> solve(A)
>>> A
{'a': 1, 'b': 200, 'x': 7, 'y': 2}

The problem with your code is that you are manipulating a and b only in the function's scope. You are not returning anything, so the program crashes as you try to print something that is never returned.

Try this solution instead:

dict = {
  "a": 1,
  "b": 200,
  "x": 2,
  "y": 7
}

def swap(a,b):
    a,b = b,a
    return a,b
    
def solve(A):
    A['x'], A['y'] = swap(A['x'], A['y'])
    return A
    
print(solve(dict))

For a dictionary you can use the update method

d = {'a': 1, 'b': 200, 'x': 2, 'y': 7}
d.update({'x':d['y'], 'y':d['x']})

print(d)
{'a': 1, 'b': 200, 'x': 7, 'y': 2}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM