Question

Is it possible to add a random number create with random.randint to a Dict ? Or is it better to add it to a List. I ask because I wan to get random.randit(0,100) and check it the List or Dict have already the number that is now generated and print out the possition on which the second same number is

So I already tried it with append to a dict but that doesn' work!

EDIT

import random
randomdict = {}
numbposition = {}
def randomnumber(numb):

    for i in random.randint(0,numb+1):
        randomdict.append(i)
        if i in randomdict:
            numbposition.index(i)
            print (numbposition)
            print (randomdict)
while True:
    numb = int(input('Give me number: '))
    print(randomnumber(numb))
    break
Was it helpful?

Solution

It is certainly possible to add the value returned by random.randint to a dictionary or list; it's just an integer, and can be treated like any other. However, you cannot append to a dictionary; that syntax is for adding to the end of a list, to add a new object to a dictionary use d[key] = value. Also, dictionaries don't have an index in the same way that e.g. lists and tuples do; just a key, and no guaranteed order.

Here is an example that is close to what you're describing:

import random

l = []
for _ in range(10):
    n = random.randint(0, 10)
    print(n)
    if n not in l:
        print("New item.")
        l.append(n)
    else:
        print("Item found at index {0}.".format(l.index(n)))
print(l)

The output from this is:

2
New item.
2
Item found at index 0.
2
Item found at index 0.
1
New item.
3
New item.
10
New item.
6
New item.
4
New item.
4
Item found at index 5.
10
Item found at index 3.
[2, 1, 3, 10, 6, 4]

Edit

To add all numbers and get the largest preexisting index, you need a slight tweak:

if n not in l:
    print("New item.")
else:
    index = max(i for i, v in enumerate(l) if v == n)
    print("Item found at index {0}.".format(index))
l.append(n)

Note that append is moved to the end (so the new n isn't in the list when we look for the largest prior index) and we can no longer use list.index (which finds the first index) - a more complex calculation is required.

This gives:

0
New item.
4
New item.
10
New item.
10
Item found at index 2.
3
New item.
4
Item found at index 1.
1
New item.
8
New item.
8
Item found at index 7.
1
Item found at index 6.
[0, 4, 10, 10, 3, 4, 1, 8, 8, 1]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top