dict n**4 in python

To create a dictionary that contains the fourth power of integers up to n, you can use a dictionary comprehension like this:

main.py
n = 10
fourth_powers = {i: i**4 for i in range(1, n+1)}
print(fourth_powers)
77 chars
4 lines

Output:

main.py
{1: 1, 2: 16, 3: 81, 4: 256, 5: 625, 6: 1296, 7: 2401, 8: 4096, 9: 6561, 10: 10000}
84 chars
2 lines

The range(1, n+1) creates a sequence of integers from 1 to n (inclusive). The i**4 calculates the fourth power of each integer. Finally, the dictionary comprehension creates a new dictionary with keys as the input integers and values as the corresponding fourth power of that integer.

gistlibby LogSnag