Choose one key arbitrarily in a dictionary without iteration
Question: I just wanna make sure that in Python dictionaries there's no way to get just
a key (with no specific quality or relation to a certain value) but doing
iteration. As much as I found out you have to make a list of them by going
through the whole dictionary in a loop. Something like this:

    
    
    list_keys=[k for k in dic.keys()]
    

The thing is I just need an arbitrary key if the dictionary is not empty and
don't care about the rest. I guess iterating over a long dictionary in
addition to creation of a long list for just randomly getting a key is a whole
lot overhead, isn't it? Is there a better trick somebody can point out?

Thanks


Answer: You can use `random.choice`

    
    
    rand_key = random.choice(dict.keys())
    

And this will only work in python 2.x, in python 3.x dict.keys returns an
iterator, so you'll have to do cast it into a list -

    
    
    rand_key = random.choice(list(dict.keys()))
    

So, for example -

    
    
    import random
    d = {'rand1':'hey there', 'rand2':'you love python, I know!', 'rand3' : 'python has a method for everything!'}
    random.choice(list(d.keys()))
    

Output -

    
    
    rand1
    

