繁体   English   中英

python3选择一个随机字典

[英]python3 choose a random dictionary

我想在Python3中选择一个随机字典。 我有一个函数foob​​ar像这样:

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'])

返回多个字典,如下所示:

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

我正在创建另一个功能,以便能够选择随机词典。

我的第一步是将函数foob​​ar的结果放入这样的变量中:

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

然后对其应用随机方法:

print(random.choice(hello))

它给我一个错误TypeError:类型为'NoneType'的对象没有len()

而且,如果我打印变量hello的类型,它会给我<class 'NoneType'>

我想是因为字典是不同的实体,但是我不确定如何解决这个问题。

在这种情况下,选择随机词典的最佳方法是什么?

感谢您从Python新手那里获得的帮助。

您错过了foobar函数末尾的return response['Items']

假设response ['Items']返回字典列表,则可以简单地使用random.choice(response['Items'])

如果在任何情况下response ['Items']返回的字典都包含乘法字典。 使用key_lst=list(the_dict.keys()) print(the_dict[random.choice(key_lst)])从包含乘法dict的dict中获取随机dict

在If and else循环中,return语句已被修改。 基本上,您需要从foobar函数返回一些内容。

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'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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