rafello rafello - 1 year ago 61
Python Question

Assign items evenly to dictionary keys

I've got a list and a list of dictionaries and I want to assign items from the list to one of two keys in the dictionaries. Both keys in the dictionaries must have values assigned, no item should appear more than once in each dictionary, and the distribution of each item should be balanced.

I'm going to use fruit:

fruits = ['apple', 'orange', 'banana', 'papaya', 'kiwi']
baskets = [{'basket': 'one', 'fruit1': '', 'fruit2': ''},
{'basket': 'two', 'fruit1': '', 'fruit2': ''},
{'basket': 'three', 'fruit1': '', 'fruit2': ''},
{'basket': 'four', 'fruit1': '', 'fruit2': ''}]

The number of baskets shouldn't matter.

This is how I'm doing it at the moment:

import itertools

def in_basket(frt, bskt):
if frt in bskt.values():
return True
return False

g = itertools.cycle(fruits)
fruit = next(g)

for basket in baskets:
basket['fruit1'] = fruit
fruit = next(g)

for basket in baskets:
while True:
if not in_basket(fruit, basket):
basket['fruit2'] = fruit
fruit = next(g)

The problem with this approach is that I get an imbalance with the distribution of fruits. There could be a lot more baskets.

Is there a way to achieve a uniform distribution of fruits in each basket slot?

Edit - the output is the updated 'baskets' list, with all the fruit slots filled.

Leo Leo
Answer Source

Since the question is still not clear, this code will uniformly fill each basket with a random fruit. The weakness is that it necessarilly requires at least as many fruit choices as there are locations in baskets.

import numpy as np

for basket in baskets:
    for k in basket:
        if k!='basket':

            new_fruit = ''

            while new_fruit in list(basket.values()):
                new_fruit = np.random.choice(fruits)

            basket[k] = new_fruit
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download