Home > Net >  How do you use the random function on a dictionary within a list?
How do you use the random function on a dictionary within a list?

Time:01-24

Let's say I have a dictionary nested inside a list.

data = [
{
    'name': 'Dave',
    'born': 1949
    'country': 'United States'
},
{
    'name': 'Chris',
    'born': 1976,
    'country': 'Portugal'
},
{
    'name': 'Lisa',
    'born': 1983,
    'country': 'United States'
}
       ]

Now I want to go through the list and pick a random value from the 'name' key so it can either print out Dave, Chris or Lisa. I know that I need to loop through the list and use random.choice, but I am not sure how to do it with a dictionary within a list.

CodePudding user response:

You can use random.choice to select a random dicitonary, and then just print its name value

print(random.choice(data)['name'])

CodePudding user response:

You just need to recognize that you are still working with a list, and the elements of that list are individual dictionaries,

import random

data = [
    {
        'name': 'Dave',
        'born': 1949,
        'country': 'United States'
    },
    {
        'name': 'Chris',
        'born': 1976,
        'country': 'Portugal'
    },
    {
        'name': 'Lisa',
        'born': 1983,
        'country': 'United States'
    }
]

for i in range(5):
    temp_dict = random.choice(data)
    print(temp_dict['name'])

So you can select a random element using random.choice and then use it with any functionality that element provides. Here the element is a dictionary, to print only the name key you simply select it, temp_dict['name'].

  •  Tags:  
  • Related