简体   繁体   中英

python3 choose a random dictionary

I want to choose a random dictionary in Python3. I have a function foobar like so:

def foobar(region_name, table_name, key=None, regex=None):

    dynamodb = boto3.resource('dynamodb', region_name=region_name)
    table = dynamodb.Table(table_name)
    regex = regex
    response = table.scan(
        Select="ALL_ATTRIBUTES"
    )

    if regex:
        r = re.compile(regex)
        slots = [slot for slot in response['Items'] if r.search(slot[key])]
        for slot in slots:
            print(slot)
    else:
    print(response['Items'])

that returns multiple dictionaries like so:

{'A': 'none', 'B': 'none', 'C': 'off', 'D': 'none', 'E': 'none'}
{'A': 'foobar', 'B': 'foobar', 'C': 'off', 'D': 'foobar', 'E': 'none'}
{'A': 'magic', 'B': 'none', 'C': 'off', 'D': 'magic', 'E': 'none'}

I am creating another function to be able to choose a random dictionary.

My first step was to put the outcome of the function foobar into a variable like so:

hello = foobar(region_name, table_name, key, regex)

And then apply the random method to it:

print(random.choice(hello))

It gives me an error TypeError: object of type 'NoneType' has no len()

Moreover, if I print the type of the variable hello , it gives me <class 'NoneType'>

I imagine it is because the dictionaries are different entities but I am not sure how to tackle this.

What is the best way to select a random dictionary in that case?

Thank you for your help from a newbie in Python.

You missed return response['Items'] in the end of foobar function

Assuming response['Items'] returns a list of dict, you can simply use random.choice(response['Items'])

If in any case response['Items'] returns a dict contains multiply dicts. Use key_lst=list(the_dict.keys()) print(the_dict[random.choice(key_lst)]) to get random dict from a dict contains multiply dicts

In the If and else loop the return statements have been modified. Basically you need to return something from the foobar function.

def foobar(region_name, table_name, key=None, regex=None):    
    '''
    Returns empty list If regex is False
    else If regex is True then returns a
    list of dictionaries.
    '''
    dynamodb = boto3.resource('dynamodb', region_name=region_name)
    table = dynamodb.Table(table_name)
    regex = regex  # This is redundant
    response = table.scan(
        Select="ALL_ATTRIBUTES"
    )

    if regex:
        r = re.compile(regex)
        slots = [slot for slot in response['Items'] if r.search(slot[key])]
        for slot in slots:
            print(slot)
        return []
    else:
        print(response['Items'])
        return list(response['Items'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM