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!