How to pass a Dict within a function, to be used in any case if necessary?

Asked

Viewed 98 times

2

Good afternoon, I have a big keyError problem, because in my program that makes use of Dict will perform several processes, and if at some point he does not find an item in which he looks, will generate me a keyError. So I made a simple function that could help me in this case.However I don’t see a way to standardize this function created to use in several dicts, just passing the key values to make such a change. Working: It assigns a new item to another item that already contains value. After that it will delete the old item I want to replace.

The function was used to adjust the following test Dict, x = {'Name':'Mark','Age':21}

    def Test(dictionary):
        dictionary['Name1'] = dictionary['Name']
        del dictionary['Name']
        return dictionary

print(Test(x))

{'Name1':'Mark', 'Age':21}

I would like it to be in a format that can be used for any case.

def Test(dictionary):
    newkey = oldkey
    del oldkey
    return dictionary

2 answers

3

The @Breno response was very good, I will only complement if you want to change more than one key in the same function call ChangeDictKey:

def ChangeDictKey(dictionary, oldKeys, newKeys):
    for oldKey, newKey in zip(oldKeys, newKeys):
        dictionary[newKey] = dictionary[oldKey]
        del dictionary[oldKey]

dictionary = {'Name': 'John Doe', 'Age': 21}
ChangeDictKey(dictionary, ['Age', 'Name'], ['Marriage Age', 'Original Name'])

>>> print(dictionary)
{'Marriage Age': 21, 'Original Name': 'John Doe'}

In this approach, one should always pass the key arguments within lists or tuples (even to exchange only one key).

  • 2

    The cool thing is that there are still numerous ways to apply this. How to use the parameter **kwargs*, calling the function with ChangeDictKey(dictionary, Name='Original Name', Age='Marriage Age') .

2


You can (and should) add two more arguments to function: oldKey and newKey. So, when you call this function, you can now modify with dynamic data.

def ChangeDictKey(dictionary, oldKey, newKey):
    dictionary[newKey] = dictionary[oldKey]
    del dictionary[oldKey]
    return dictionary

dictionary = {'Name': 'John Doe', 'Age': 21}
dictionary = ChangeDictKey(dictionary, 'Age', 'Marriage Age')
print(dictionary)

But as dictionaries are mutable, you can leave the function with no return. Join processing it. That is, so:

def ChangeDictKey(dictionary, oldKey, newKey):
    dictionary[newKey] = dictionary[oldKey]
    del dictionary[oldKey]

dictionary = {'Name': 'John Doe', 'Age': 21}
ChangeDictKey(dictionary, 'Age', 'Marriage Age')
print(dictionary)
  • 1

    Thanks Breno, I was passing values between conchetes at the time of calling the function for such Dict, Solved! Abrss

Browser other questions tagged

You are not signed in. Login or sign up in order to post.