Q:

python: proper use of dictionaries

i try to create a function, which generates random int-values and after a value appeared twice the function should return the number of all generated int-values.
I have to use a dictionary.
This is my code so far:
def repeat(a,b):
    dict={}
    d=b-a+2
    for c in range(1,d):
        dict['c']=random.randint(a,b)
        for f in dict:
            if dict['f']==dict['c']:
                return c

First problem: It doesn't work.
>>> repeat(1,5)
Traceback (most recent call last):
  File "<pyshell#144>", line 1, in <module>
    repeat(1,5)
  File "<pyshell#143>", line 7, in repeat
    if dict['f']==dict['c']:
KeyError: 'f'

Second problem: if dict['f']==dict['c']:
Should be true in first step because both values are the same.
I can't find a smart way to compare all values without comparing a key with itself.
Sorry for my bad english, it's kinda rusty and thank you for your time.

A:

Enclosing your variable names in quotes makes them strings - Python is looking for the key of the letter f, not the key with the integer in the f variable.
Simply use the variable normally and it should work as you expected:
def repeat(a, b):
    stored = {}
    d = b - a + 2
    for c in range(1, d):
        stored[c] = random.randint(a, b)
        for f in stored:
            if stored[f] == stored[c]:
                return c

Note also that you are shadowing the built-in function dict() by naming your variable dict - it is preferable to use another name because of this.

