Skip to content Skip to sidebar Skip to footer

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 foun

Solution 1:

A lot of the answers here produce a random key but the original question asked for an arbitrary key. There's quite a difference between those two. Randomness has a handful of mathematical/statistical guarantees.

Python dictionaries are not ordered in any meaningful way. So, yes, accessing an arbitrary key requires iteration. But for a single arbitrary key, we do not need to iterate the entire dictionary. The built-in functions next and iter are useful here:

key = next(iter(mapping))

The iter built-in creates an iterator over the keys in the mapping. The iteration order will be arbitrary. The next built-in returns the first item from the iterator. Iterating the whole mapping is not necessary for an arbitrary key.

If you're going to end up deleting the key from the mapping, you may instead use dict.popitem. Here's the docstring:

D.popitem() -> (k, v), removeandreturnsome (key, value) pair as a 2-tuple;
but raise KeyError if D is empty.

Solution 2:

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 -

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

Output -

rand1

Solution 3:

You are correct: there is not a way to get a random key from an ordinary dict without using iteration. Even solutions like random.choice must iterate through the dictionary in the background.

However you could use a sorted dict:

from sortedcontainers import SortedDict as sd

d = sd(dic)
i = random.randrange(len(d))
ran_key = d.iloc[i]

More here:.

http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html

Note that whether or not using something like SortedDict will result in any efficiency gains is going to be entirely dependent upon the actual implementation. If you are creating a lot of SD objects, or adding new keys very often (which have to be sorted), and are only getting a random key occasionally in relation to those other two tasks, you are unlikely to see much of a performance gain.

Solution 4:

How about something like this:

importrandomarbitrary_key= random.choice( dic.keys() )

BTW, your use of a list comprehension there really makes no sense:

dic.keys() == [k forkin dic.keys()]

Solution 5:

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

import randomiflen(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]

Post a Comment for "Choose One Key Arbitrarily In A Dictionary Without Iteration"