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

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 09:20:30457browse

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'}

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

items = list(d.items())

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

item = random.choice(items)

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

(country, capital) = item

What if you only need the key or the value?

Choosing Random Keys:

key = random.choice(list(d.keys()))

Choosing Random Values:

value = random.choice(list(d.values()))

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!

Statement:
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