-2

How to to accept the length of a dictionary, then create key-value pairs where the key is a random integer in the range 1 to 100 and the value is the square of the integer? If I enters 5, then the output should be:

{68: 4624, 28: 784, 99: 9801, 15: 225, 6: 36}

I did some of the code, but cannot to combine with each other. I don't know where to add random

d=dict() 
n=int(input("Enter a number in the range 1 to 100: ")) for i in range (100): 
d[i]=i**i 
print(d)

1 Answers1

1

You can use random.sample to ensure having different keys (duplicated random values would result in less elements than the target as dictionary keys are unique), and a dictionary comprehension:

from random import sample

n = input('number of values: ')

out = {k: k**2 for k in sample(range(1,101), n)}

Example:

{79: 6241, 80: 6400, 81: 6561, 62: 3844, 50: 2500}
mozway
  • 194,879
  • 13
  • 39
  • 75
  • 4
    This isn't a code-writing service, please don't encourage people to treat it like one. – jonrsharpe Mar 03 '22 at 22:48
  • @jonrsharpe I understand your point but I am afraid this is a lost cause. I'd rather try to give a useful answer than letting it attract low quality answers. – mozway Mar 03 '22 at 22:52
  • You can prevent it from attracting low quality answers by _voting to close it_. Answering low-effort requirement dumps just encourages more of them. – jonrsharpe Mar 03 '22 at 22:53
  • I don't believe the latter statement, I feel that low quality questions will always exist no matter what. It is just too easy to post a question. I prefer trying to turn them into potentially useful Q/A if I think there is a bit of interesting thing. Here I thought it was the case. I do vote/close a fair share of questions/duplicates though ;) – mozway Mar 03 '22 at 22:55
  • @jonrsharpe I also realized that many useful Q/A started as no-attempt questions ([example](https://stackoverflow.com/questions/11346283/renaming-column-names-in-pandas)) – mozway Mar 03 '22 at 23:04