Home > Net >  Populate Python dictionaries with pre-assigned keys and values of a particular length
Populate Python dictionaries with pre-assigned keys and values of a particular length

Time:10-05

Say for example I have the following dictionary in Python:

memory_map = {'data': [1,2,3], 'theta': [4,5,6,7]}

I would like to create another random dictionary that is identical to memory_map, has the same keys and the same lengths of lists as their values however the elements of the list are populated with random values using the np.random.default_rng(seed).uniform(low, high, size) function.

An example would be: random_dict = {'data': [5,3,1], 'theta': [7,3,4,8]}.

Moreover, if the names of the keys or the lengths of the lists in values change, this should automatically be reflected in the random_dict that is created.

If I add a new key or remove a key from the memory_map this should also be reflected in the random_dict.

So far, I have random_dict = {item: [] for item in list(memory_map.keys())} but am unsure of how to populate the empty list with the random values of the same length.

Thanks.

CodePudding user response:

Looks like you want something like this.

import random
import itertools


def shuffle_map(input_map):
    # Grab a list of all values
    all_values = list(itertools.chain(*input_map.values()))
    random.shuffle(all_values)  # Shuffle it

    new_map = {}  # Initialize a new map
    i = 0  # Keep track of how many items we've consumed
    for key, value in input_map.items():
        n = len(value)  # How many values per this key
        new_map[key] = all_values[i : i   n]  # Assign a slice
        i  = n

    return new_map


memory_map = {"data": [1, 2, 3], "theta": [4, 5, 6, 7]}
print(shuffle_map(memory_map))

This prints out (e.g., consecutive runs)

{'data': [1, 5, 7], 'theta': [2, 4, 3, 6]}
{'data': [6, 7, 1], 'theta': [5, 4, 3, 2]}
{'data': [5, 2, 3], 'theta': [7, 6, 4, 1]}

CodePudding user response:

For the random lists you should take a look at the random module in the standard library, specifically at the random.sample or random.choices, depending on your needs. For the second request, of automatically update the dictionary based on changes of the first, the easiest way to do it is to create a wrapper around the first dict inheriting from the collections.UserDict class

  • Related