Categories
Python Answers

How to reverse or invert a dictionary mapping with Python?

Sometimes, we want to reverse or invert a dictionary mapping with Python.

In this article, we’ll look at how to reverse or invert a dictionary mapping with Python.

How to reverse or invert a dictionary mapping with Python?

To reverse or invert a dictionary mapping with Python, we can use the items method of the dictionary to get the items and then use dictionary comprehension to flip the keys and values.

For instance, we write:

my_map = {'a': 1, 'b': 2}
inv_map = {v: k for k, v in my_map.items()}
print(inv_map)

We call my_map.items to return the key and value of each entry as k and v respectively.

Then we flip them by putting v to the left of the colon and k after.

And then we assign the returned dictionary to inv_map.

Therefore, inv_map is {1: 'a', 2: 'b'}.

Conclusion

To reverse or invert a dictionary mapping with Python, we can use the items method of the dictionary to get the items and then use dictionary comprehension to flip the keys and values.

Categories
Python Answers

How to POST JSON data with Python Requests?

Sometimes, we want to POST JSON data with Python Requests.

In this article, we’ll look at how to POST JSON data with Python Requests.

How to POST JSON data with Python Requests?

To POST JSON data with Python Requests, we call the requests.post method.

For instance, we write:

import requests

r = requests.post('http://httpbin.org/post', json={"key": "value"})
print(r.status_code)
print(r.json())

We call requests.post with the URL to make request to and the json request payload.

The response object is the returned and assigned to r.

We get the status code from r.status_code and the response body from r.json.

r.status_code should be 200.

And r.json should return:

{'args': {}, 'data': '{"key": "value"}', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '16', 'Content-Type': 'application/json', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.26.0', 'X-Amzn-Trace-Id': 'Root=1-616c8c56-6e89c2ab7addbeee5064302c'}, 'json': {'key': 'value'}, 'origin': '35.197.57.70', 'url': 'http://httpbin.org/post'}

Conclusion

To POST JSON data with Python Requests, we call the requests.post method.

Categories
Python Answers

How to use getters and setters with Python?

Sometimes, we want to use getters and setters with Python.

In this article, we’ll look at how to use getters and setters with Python.

How to use getters and setters with Python?

To use getters and setters with Python, we can use the property, setter and deleter decorators.

deleter is called when the del keyword is used to remove an attribute from an object.

For instance, we write:

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        print("getter of x called")
        return self._x

    @x.setter
    def x(self, value):
        print("setter of x called")
        self._x = value

    @x.deleter
    def x(self):
        print("deleter of x called")
        del self._x


c = C()
c.x = 'foo'
foo = c.x
del c.x

We have the C class with the x getter which has the property decorator applied to it and returns self._x.

The x setter has the x.setter called on it and sets self._x to value.

value is the value that we assign to x.

The x deleter has the x.deleter used on it and uses the del operator to remove the self._x property.

Then we instantiate C and assigns it to c.

And then we set c.x to 'foo', assigns c.x fo foo, and use del to remove the c.x attribute.

Therefore, we see:

setter of x called
getter of x called
deleter of x called

printed.

Conclusion

To use getters and setters with Python, we can use the property, setter and deleter decorators.

deleter is called when the del keyword is used to remove an attribute from an object.

Categories
Python Answers

How to get a list of numbers as input from the user with Python?

Sometimes, we want to get a list of numbers as input from the user with Python.

In this article, we’ll look at how to get a list of numbers as input from the user with Python.

How to get a list of numbers as input from the user with Python?

To get a list of numbers as input from the user with Python, we can use list comprehension.

For instance, we write:

a = [int(x) for x in input().split()]
print(a)

to call input to get the input from the user.

And then we call split to split the inputted string by the spaces.

Then we call int to convert each entry from the split string to an int.

And finally, we assign the list to a.

Therefore, a is [1, 2].

Conclusion

To get a list of numbers as input from the user with Python, we can use list comprehension.

Categories
Python Answers

How to access nested dictionary items via a list of keys with Python?

Sometimes, we want to access nested dictionary items via a list of keys with Python.

In this article, we’ll look at how to access nested dictionary items via a list of keys with Python.

How to access nested dictionary items via a list of keys with Python?

To access nested dictionary items via a list of keys with Python, we can use the reduce function with the operator.getitem method to get the dictionary item with the array of keys forming the path to the dictionary item.

For instance, we write:

from functools import reduce
import operator


def getFromDict(data_dict, map_list):
    return reduce(operator.getitem, map_list, data_dict)


def setInDict(data_dict, map_list, value):
    getFromDict(data_dict, map_list[:-1])[map_list[-1]] = value


data_dict = {
    "a": {
        "r": 1,
        "s": 2,
        "t": 3
    },
    "b": {
        "u": 1,
        "v": {
            "x": 1,
            "y": 2,
            "z": 3
        },
        "w": 3
    }
}

map_list = ["a", "r"]

setInDict(data_dict, map_list, 100)
print(data_dict)

We have the getFromDict function that calls reduce with the mapList and dataDict to get the item from data_dict with the path of the dictionary formed by map_list list.

Then we have the setInDict function that use getFromDict with the data_dict and map_list to get dictionary item from data_dict with the path to the item formed by map_list.

Then we set the value of the retrieved dictionary item to value.

Next, we call setInDict with data_dict, map_list and 100 to set data_list['a']['r'] to 100.

Therefore, data_dict is now:

{'a': {'r': 100, 's': 2, 't': 3}, 'b': {'u': 1, 'v': {'x': 1, 'y': 2, 'z': 3}, 'w': 3}}

Conclusion

To access nested dictionary items via a list of keys with Python, we can use the reduce function with the operator.getitem method to get the dictionary item with the array of keys forming the path to the dictionary item.