loops - Add random number of key-value pair to dictionary in Python -


my question how can add random number of {(name, f), (parameters, []}) object dictionary loop iteration (i see loop way solve it). in example have 1 finding specified, if want have several (random number in range)? have array of f's , relevant parameters, want have different number of findings each time i'm running code.

"findings": [{ #constructor bson     "name": f,     "parameters": [parameters, parameters2, parameters3] }, {.. }] 

you try following. assuming want random number of name f (likely f str) findings associated parameters (a list) appended dict list (which value part of dictionary key findings). assuming have function get_params take f (name?) argument , returns list of parameters.

import random  # ... # random number of f's f_list (your list of f's) # note: don't more have in list max_num_f = min(10, len(f_list)) num_f = random.randint(0, max_num_f) # initial index take slice f_list index = random.randint(0, len(f_list) - num_f)  # iterate on slice of f's chosen, params , add dict f in f_list[index : index+num_f]:     # if findings key missing, add     if 'findings' not in findings_dict:         findings_dict['findings'] = []     # add findings dict list     findings_dict['findings'].append({'name' : f, 'parameters' : get_params(f)}) 

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -