Pythonic way to access arbitrary element from dictionary

后端 未结 4 776
萌比男神i
萌比男神i 2020-12-06 16:33

I have a dictionary, full of items. I want to peek at a single, arbitrary item:

print("Amongst our dictionary\'s items are such diverse elements as: %s&q         


        
4条回答
  •  情书的邮戳
    2020-12-06 16:53

    Why not use random?

    import random
    
    def arb(dictionary):
        return random.choice(dictionary.values())
    

    This makes it very clear that the result is meant to be purely arbitrary and not an implementation side-effect. Until performance becomes an actual issue, always go with clarity over speed.

    It's a shame that dict_values don't support indexing, it'd be nice to be able to pass in the value view instead.

    Update: since everyone is so obsessed with performance, the above function takes <120ms to return a random value from a dict of 1 million items. Relying on clear code is not the amazing performance hit it's being made out to be.

提交回复
热议问题