Python使用random.shuffle()随机打乱字典排序

示例.1

import random
from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)
print(x)

运行结果:
[[1], [2], [5], [0], [7], [9], [3], [8], [4], [6]]
[[6], [0], [7], [1], [3], [9], [5], [2], [4], [8]]

示例.2

dicts = {
    "productCode": "xyd",
    "account": "phone",
    "appType": "ios",
    "channelCode": "AppStore",
    "event": "FORGET_PWD"
}

def random_dic(dicts):
    dict_key_ls = list(dicts.keys())
    random.shuffle(dict_key_ls)
    new_dic = {}
    for key in dict_key_ls:
        new_dic[key] = dicts.get(key)
    return new_dic


print(random_dic(dicts))

运行结果:
{'channelCode': 'AppStore', 'productCode': 'xyd', 'appType': 'ios', 'event': 'FORGET_PWD', 'account': 'phone'}

posted @ 2021-01-20 15:37  莫贞俊晗  阅读(4652)  评论(0编辑  收藏  举报