Anonymous
Anonymous

Reputation: 11

Difficulty with dictionary order function

Write a function named "indexed_kvs" that doesn't take any parameters and returns a new key-value store containing the integers from 0 to 36 as values each stored at a key which is a string containing the digits of the integer. For example the key-value "0":0 will be in your returned key-value store (include both 0 and 36 in your list). (My code below)

def indexed_kvs():
    d = dict()
    for x in range(37):
        d[x] = x
        return d

I keep on getting the first key and value; how do I get all the keys and values?

Upvotes: 1

Views: 135

Answers (3)

user2390182
user2390182

Reputation: 73498

You return from inside the loop which is a common mistake that can be avoided altogether by using a dict comprehension, at least in this simple case:

def indexed_kvs():
    return {str(x): x for x in range(37)}

Upvotes: 2

Eshita Shukla
Eshita Shukla

Reputation: 811

You have your "return d", inside you loop. So, what happens is that -

1) The function begins

2) The for loop executes once:

a) adds 0 to the dictionary at key 0,

b) encounters return d, them thinks- 'Okay! I got a return statement. I gotta exit! '

c) And Boom! Your function is done with

So, just move your return d out of you for loop. So, the exiting of the function will take place when, the loop is over.

So your new code should be:

def indexed_kvs():
    d = dict()
    for x in range(37):
        d[str(x)] = x
    return d

Upvotes: 0

Hemerson Tacon
Hemerson Tacon

Reputation: 2522

As @Loocid comment, the return statement shouldn't be inside the for loop, so the correct code would be:

def indexed_kvs():
    d = dict()
    for x in range(37):
        d[str(x)] = x
    return d

Upvotes: 0

Related Questions