Home > Backend Development > Python Tutorial > How to Access Random Key-Value Pairs from Dictionaries in Python?

How to Access Random Key-Value Pairs from Dictionaries in Python?

Linda Hamilton
Release: 2024-11-04 09:20:30
Original
537 people have browsed it

How to Access Random Key-Value Pairs from Dictionaries in Python?

Accessing Random Key-Value Pairs from Dictionaries in Python

Want to pick a random key-value pair from a dictionary? In Python, you can do this with ease.

Consider a dictionary:

d = {'VENEZUELA': 'CARACAS', 'CANADA': 'OTTAWA'}
Copy after login

To select a random item (key-value pair), simply create a list of the dictionary's items:

items = list(d.items())
Copy after login

Then, use random.choice() to choose an item randomly:

item = random.choice(items)
Copy after login

item will now be a tuple containing the random key and value:

(country, capital) = item
Copy after login

What if you only need the key or the value?

Choosing Random Keys:

key = random.choice(list(d.keys()))
Copy after login

Choosing Random Values:

value = random.choice(list(d.values()))
Copy after login

This optimized approach avoids creating a list of tuples.

The above is the detailed content of How to Access Random Key-Value Pairs from Dictionaries in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template