Ali Ali - 5 months ago 20
Python Question

Choose one key arbitrarily in a dictionary without iteration

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

check the length of dictionary like this, this should do !!

import random

if len(yourdict) > 0:
    randomKey = random.sample(yourdict,1)
    print randomKey[0]
else:
    do something

randomKey will return a list, as we have passed 1 so it will return list with 1 key and then get the key by using randomKey[0]

Comments