Python выбрать случайный элемент словаря

Get Random Value from Dictionary in Python

To get a random value from a dictionary in Python, you can use the random module choice() function, list() function and dictionary values() function.

import random d = print(random.choice(list(d.values()))) #Output: 5

If you want to get a random key from a dictionary, you can use the dictionary keys() function instead.

import random d = print(random.choice(list(d.keys()))) #Output: d

If you want to get a random key/value pair from a dictionary, you can use the dictionary items() function.

import random d = print(random.choice(list(d.items()))) #Output: ('b',5)

When working with different collections of data, to be able to get a random piece of information from your data can be valuable.

In Python, many times we are working with dictionaries.

We can get a random value from a dictionary easily in Python using the random module choice() function – all we need to do is pass a list of the dictionary values.

To get the dictionary values, we can use the dictionary values() function and convert it to a list using list()

Читайте также:  Jest encountered an unexpected token css

Below shows you an example of how to get a random value from a dictionary variable in Python.

import random d = print(random.choice(list(d.values()))) #Output: 5

Get Random Key from Dictionary Using Python

If you want to get a random key from a dictionary, you can use the dictionary keys() function instead of the values() function.

Below shows you an example of how to get a random key from a dictionary variable in Python.

import random d = print(random.choice(list(d.keys()))) #Output: d

Get Random Key/Value Pair from Dictionary Using Python

If you want to get a random key/value pair from a dictionary, you can use the dictionary items() function.

Below shows you an example of how to get a random key/value pair from a dictionary variable in Python.

import random d = print(random.choice(list(d.items()))) #Output: ('b',5)

Hopefully this article has been useful for you to learn how to get random values from a dictionary in Python.

  • 1. Python Increment Counter with += Increment Operator
  • 2. Does Python Use Semicolons? Why Python Doesn’t Use Semicolons
  • 3. Convert String to Boolean Value in Python
  • 4. pandas ewm – Calculate Exponentially Weighted Statistics in DataFrame
  • 5. Get Month Name from Date in Python
  • 6. Using if in Python Lambda Expression
  • 7. Python Indicator Function – Apply Indicator Function to List of Numbers
  • 8. Python if else do nothing – Using pass Statement to Do Nothing in Python
  • 9. Python Destroy Object – How to Delete Objects with del Keyword
  • 10. Check if All Elements in Array are Equal in Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

Python выбрать случайный элемент словаря

Last updated: Feb 21, 2023
Reading time · 4 min

banner

# Table of Contents

# Get random key and value from a dictionary in Python

To get a random key-value pair from a dictionary:

  1. Use the dict.items() method to get a view of the dictionary’s items.
  2. Use the list() class to convert the view to a list.
  3. Use the random.choice() method to get a random key-value pair from the dictionary.
Copied!
import random my_dict = 'name': 'Borislav Hadzhiev', 'fruit': 'apple', 'number': 5, 'website': 'bobbyhadz.com', 'topic': 'Python' > # ✅ get random key-value pair from dictionary key, value = random.choice(list(my_dict.items())) print(key, value) # 👉️ name Borislav Hadzhiev # ----------------------------------------------- # ✅ get random key from dictionary key = random.choice(list(my_dict)) print(key) # 👉️ topic # ----------------------------------------------- # ✅ get random value from dictionary value = random.choice(list(my_dict.values())) print(value) # 👉️ bobbyhadz.com

get random key and value from dictionary

The dict.items method returns a new view of the dictionary’s items ((key, value) pairs).

Copied!
my_dict = 'name': 'Borislav Hadzhiev', 'fruit': 'apple', 'number': 5, 'website': 'bobbyhadz.com', 'topic': 'Python' > # 👇️ dict_items([('name', 'Borislav Hadzhiev'), ('fruit', 'apple'), ('number', 5), ('website', 'bobbyhadz.com'), ('topic', 'Python')]) print(my_dict.items())

We used the list() class to convert the view of key-value pairs to a list before passing it to the random.choice() method.

The list class takes an iterable and returns a list object.

The random.choice method takes a sequence and returns a random element from the non-empty sequence.

Copied!
import random my_dict = 'name': 'Borislav Hadzhiev', 'fruit': 'apple', 'number': 5, 'website': 'bobbyhadz.com', 'topic': 'Python' > key, value = random.choice(list(my_dict.items())) print(key, value) # 👉️ website bobbyhadz.com

using random choice method

If the sequence is empty, the random.choice() method raises an IndexError .

# Get a random key from a dictionary in Python

This is a two-step process:

  1. Use the list() class to convert the dictionary to a list of keys.
  2. Use the random.choice() method to get a random key from the list.
Copied!
import random my_dict = 'name': 'Borislav Hadzhiev', 'fruit': 'apple', 'number': 5, 'website': 'bobbyhadz.com', 'topic': 'Python' > key = random.choice(list(my_dict)) print(key) # 👉️ topic

get random key from dictionary

We used the list() class to convert the dictionary to a list of keys.

Copied!
my_dict = 'name': 'Borislav Hadzhiev', 'fruit': 'apple', 'number': 5, 'website': 'bobbyhadz.com', 'topic': 'Python' > # 👇️ ['name', 'fruit', 'number', 'website', 'topic'] print(list(my_dict)) # 👇️ ['name', 'fruit', 'number', 'website', 'topic'] print(list(my_dict.keys()))

The dict.keys method returns a new view of the dictionary’s keys.

The last step is to pass the list of keys to the random.choice() method to get a random key.

# Get a random value from a dictionary in Python

This is a three-step process:

  1. Use the dict.values() method to get a view of the dictionary’s values.
  2. Use the list() class to convert the view object to a list.
  3. Use the random.choice() method to get a random value from the dictionary.
Copied!
import random my_dict = 'name': 'Borislav Hadzhiev', 'fruit': 'apple', 'number': 5, 'website': 'bobbyhadz.com', 'topic': 'Python' > value = random.choice(list(my_dict.values())) print(value) # 👉️ Borislav Hadzhiev

get random value from dictionary in python

The dict.values method returns a new view of the dictionary’s values.

Copied!
import random my_dict = 'name': 'Borislav Hadzhiev', 'fruit': 'apple', 'number': 5, 'website': 'bobbyhadz.com', 'topic': 'Python' > # 👇️ dict_values(['Borislav Hadzhiev', 'apple', 5, 'bobbyhadz.com', 'Python']) print(my_dict.values())

We used the list() class to convert the view object to a list and used the random.choice() method to get a random value from the list.

# Get multiple random keys and values from a Dictionary in Python

If you need to get multiple random keys and values from a dictionary, use the random.sample() method.

Copied!
import random my_dict = 'id': 1, 'name': 'Bobbyhadz', 'age': 30, 'country': 'Chile', 'city': 'Santiago', > random_keys = random.sample(list(my_dict), 2) print(random_keys) # 👉️ ['age', 'name'] random_values = random.sample(list(my_dict.values()), 2) print(random_values) # 👉️ [30, 'Bobbyhadz'] random_items = random.sample(list(my_dict.items()), 2) print(random_items) # 👉️ [('country', 'Chile'), ('id', 1)]

get multiple random keys and values from dictionary

The random.sample method returns a list of N unique elements chosen from the provided sequence.

The first argument the method takes is a sequence and the second is the number of random elements to be returned.

Notice that we used the list() class to convert the dictionary’s keys, values and items to lists in the call to random.sample() .

We can’t directly pass a dictionary to the random.sample() method.

# Get multiple random keys and values from a Dictionary using random.choices()

You can also use the random.choices() method to get multiple random keys and values from a dictionary.

Copied!
import random my_dict = 'id': 1, 'name': 'Bobbyhadz', 'age': 30, 'country': 'Chile', 'city': 'Santiago', > random_keys = random.choices(list(my_dict), k=2) print(random_keys) # 👉️ ['name', 'country'] random_values = random.choices(list(my_dict.values()), k=2) print(random_values) # 👉️ ['Santiago', 30] random_items = random.choices(list(my_dict.items()), k=2) print(random_items) # 👉️ [('id', 1), ('city', 'Santiago')]

The random.choices method returns a k sized list of elements chosen from the provided iterable with replacement.

If the iterable is empty, the method raises an IndexError exception.

Copied!
import random my_dict = 'id': 1, 'name': 'Bobbyhadz', 'age': 30, 'country': 'Chile', 'city': 'Santiago', > random_keys = random.choices(list(my_dict), k=3) print(random_keys) # 👉️ ['city', 'city', 'name'] random_values = random.choices(list(my_dict.values()), k=3) print(random_values) # 👉️ ['Santiago', 1, 'Santiago'] random_items = random.choices(list(my_dict.items()), k=3) # 👇️ [('age', 30), ('name', 'Bobbyhadz'), ('name', 'Bobbyhadz')] print(random_items)

Notice that when using the random.choices() method it is possible to get repeated values.

This is not the case when using the random.sample() method.

The random.sample() method can never return repeated values.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to select randomly keys from a dictionary in python 3 ?

Examples of how to select randomly keys from a list in python 3:

Create a dictionary

Lets first create a dictionary in python

Select randomly a key using random.choice()

To select a random key from a dictionary, a solution is to use random.choice():

import random random.choice(list(d)) 

choice can be used multiple times to select randomly multiple elements:

To create a list of keys random selected randomly, a solution is to use a list comprehension:

r = [random.choice(list(d)) for i in range(2)] 

Another example with 10 elements selected radnomly:

r = [random.choice(list(d)) for i in range(10)] 

Note: to get always the same output, a solution is to use a seed:

random.seed(42) r = [random.choice(list(d)) for i in range(10)] 

will always returns the same.

Create a random sample using random.sample()

Another solution is to create a sample without replacement:

where l is the list and n the sample’s size ( n

References

Benjamin

Greetings, I am Ben! I completed my PhD in Atmospheric Science from the University of Lille, France. Subsequently, for 12 years I was employed at NASA as a Research Scientist focusing on Earth remote sensing. Presently, I work with NOAA concentrating on satellite-based Active Fire detection. Python, Machine Learning and Open Science are special areas of interest to me.

Skills

Источник

Оцените статью