Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Dictionaries Key Management

How to get a random key:value tuple from dictionary?

The notes below the video describe .popitem() as returning a random key:value pair as a tuple, but it actually seems to be just a set seed that returns an arbitrary pair, based on the internal ordering of the dictionary, as it will return the same tuple sequence every time the program is run. In my experience "arbitrary" != "random" in nearly all cases I have come across.

I'm having some issues with getting a tuple to return while using

my_dict.pop( random.choice( list( my_dict ) ) )

variation. I can return random values just fine, but how would I actually retrieve the key:value pair instead? Everything I've tried has come up with errors, usually referring to lists not being hashable, or something of the kind. Any suggestions or alternative approaches would be welcome.

1 Answer

james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

one way would be to use randint instead of choice with arguments of 0 and len(my_dict)-1. let's store that in variable b. this will be the range of indices in a list of the keys of my_dict. store the list in a variable s, then you can create the tuple s[b], my_dict.get(s[b]). the tuple will be a random k:v pair from my_dict.

I see what you mean. I guess I just wanted to make sure I wasn't overlooking a better variation of random._____() that would do the job or some way of doing it besides list(my_dict) that would return a tuple instead of just the value or key, since my_dict.popitem() returns a tuple. I guess I hadn't thought of doing the easier alternative and just building the tuple myself. This will work for now, thanks.

*** Edit *** I suppose the example I used in my question wasn't the best, in practice, since simply changing it to list(my_dict.keys()) would suffice the randomness needed to replace .popitem() the way I wanted to. your answer still works beautifully for other requirements I had elsewhere, though. Thanks.