Making a dictionary that contains (i,i*i) where i is from 1 to n

Viewed 145

Input Format:

Take the number n in a single line.

Output Format:

Print the dictionary d in a single line.

Desired behaviour, for input 8, a dictionary:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

What I tried:

n=int(input())
for i in range(1,n+1):
    a=i*i
    print("{",i,": ",a,"}",sep="")

What it gives me, for input 6:

{1: 1}
{2: 4}
{3: 9}
{4: 16}
{5: 25}
{6: 36}
4 Answers

You can create the dict in a single statement:

d = dict((i,i*i) for i in range(1,n+1))

with n=8 you get

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

You can create the dictionary using a dictionary comprehension:

n = int(input())
d = {i: i * i for i in range(1, n + 1)}
print(d)

for 10 you get

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

If you want to print dictionary, why not just make one and keep it simple instead of making it complicated.

n=int(input())
d = {}
for i in range(1,n+1):
    a=i*i
    d[i] = a
print(d)

And you will get the expected O/P:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

One-line solution

print(''.join(['{', ', '.join([': '.join((str(i), str(i * i),)) for i in range(1, n + 1)]), '}']))

Explanation

There is a built-in function called join in str module. With it, you can concat a list of strings with specified seperator.

The following example

','.join(['Hello', 'World'])

will returns the concat string

'Hello, world'

You can see that join handles margins very well.

But please note that join take a single argument, list of strings. You cannot provide it with list of integers; otherwise join will raise an error saying:

TypeError: sequence item 0: expected str instance, int found

Thus you should force convert integers generated by range to strings with str.

Reference

Related