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.

Categories
Python Answers

How to concatenate str and int objects with Python?

Sometimes, we want to concatenate str and int objects with Python.

In this article, we’ll look at how to concatenate str and int objects with Python.

How to concatenate str and int objects with Python?

To concatenate str and int objects with Python, we can use the string’s format method, string interpolation or an f-string.

For instance, we write:

things = 3
s1 = 'You have %d things.' % things
s2 = 'You have {} things.'.format(things)
s3 = f'You have {things} things.'
print(s1)
print(s2)
print(s3)

We use string interpolate to create s1.

%d is a placeholder for a number within the string.

Then we put the variables we interpolate after the % sign.

To create s2, we put curly braces in the string for the placeholder.

Then we call format on the string with the variables we want to interpolate.

Finally, we create s3 with the f prefix and the variable right inside the string surrounded by curly braces.

f-strings are available since Python 3.6.

Therefore, s1, s2, and s3 are all 'You have 3 things.'.

Conclusion

To concatenate str and int objects with Python, we can use the string’s format method, string interpolation or an f-string.

Categories
Python Answers

How to transpose a list of lists with Python?

Sometimes, we want to transpose a list of lists with Python.

In this article, we’ll look at how to transpose a list of lists with Python.

How to transpose a list of lists with Python?

To transpose a list of lists with Python, we can use the map function with the itertools.zip_longest method.

itertools.zip_longest lets us transpose any nested arrays including jagged ones.

For instance, we write:

import itertools

l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
t = list(map(list, itertools.zip_longest(*l, fillvalue=None)))
print(t)

We call map with list and the array created by itertools.zip_longest which takes the item from each nested array and returned.

fillvalue is set to None so that lists that are shorter than the longest one in the list will have None added to them so that they match the length of the longest list.

Then we call list to convert the returned map with the transposed nested lists back to a nested list.

Therefore, t is [[1, 4, 7], [2, 5, 8], [3, 6, 9]].

Conclusion

To transpose a list of lists with Python, we can use the map function with the itertools.zip_longest method.

itertools.zip_longest lets us transpose any nested arrays including jagged ones.

Categories
Python Answers

How to read a big file in Python?

Sometimes, we want to read a big file in Python.

In this article, we’ll look at how to read a big file in Python.

How to read a big file in Python?

To read a big file in Python, we can call the readlines method on the opened file object with the buffer size.

For instance, we write:

BUF_SIZE = 100

bigfile = open('bar.txt', 'r')
tmp_lines = bigfile.readlines(BUF_SIZE)
while tmp_lines:
    print(tmp_lines)
    tmp_lines = bigfile.readlines(BUF_SIZE)

to call open with the file path of the file and 'r' to open the file with read permission.

Then we call bigfile.readlines with the BUF_SIZE buffer size.

BUF_SIZE is in bytes.

Next, we have a while loop that runs while tmp_lines isn’t None.

In the while loop, we call bigfile_readlines to read the next chunk in the buffer.

Conclusion

To read a big file in Python, we can call the readlines method on the opened file object with the buffer size.