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]