Cat Hariss
Cat Hariss

Reputation: 143

Find dynamic dictionary key values duplicates

I am creating a dynamic dictionary like this:

a_list = ("Item1", "Item2", "Item3")
b_list = ("Item4", "Item5")
c_list = ("Item6", "Item7", "Item8", "Item9")

dct = {}

for x in range(100):

    dct['key_%s' % x] = []

    a = random.choice(a_list)
    dct['key_%s' % x].append(a)
    b = random.choice(b_list)
    dct['key_%s' % x].append(b)
    c = random.choice(c_list)
    dct['key_%s' % x].append(c)

where I populate each new key_ with a list of items a, b, c that get random values from a_list, b_list, c_list

Now I want to only have unique a, b, c values for each key in the dct dictionary so after finishing appending I would like to compare the last dictionary item to all of the previous ones and if a duplicate is found maybe remove that key pair and decrease the x so it will try adding another a, b, c value combination.

This is what I have also tried:

dct_values = list(dct.values())

if len(dct_values) > 1:
    last_item = list(dct.values())[-1]
    for allists in list(dct.values())[0:-1]:
        if last_item == allists:
            print(f"Duplicate found on {x} >> {last_item}")
            dct.popitem()
            x = x - 1

This will give me unique values but the key_# is not consecutive and the code looks ugly

The expected result is a dictionary with unique list key values from the a, b, c _list

Upvotes: 0

Views: 96

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195418

IIUC, you can use generator that yield random unique items:

import random


a_list = ("Item1", "Item2", "Item3")
b_list = ("Item4", "Item5")
c_list = ("Item6", "Item7", "Item8", "Item9")


def get_items(*lists):
    duplicates = set()
    while True:
        items = tuple(random.choice(l) for l in lists)
        if items not in duplicates:
            duplicates.add(items)
            yield items


dct = {
    f"key_{i}": items
    for i, items in zip(range(10), get_items(a_list, b_list, c_list))
}

print(dct)

Prints (for example):

{
    "key_0": ("Item3", "Item4", "Item9"),
    "key_1": ("Item2", "Item5", "Item8"),
    "key_2": ("Item2", "Item4", "Item6"),
    "key_3": ("Item1", "Item4", "Item6"),
    "key_4": ("Item1", "Item5", "Item7"),
    "key_5": ("Item2", "Item5", "Item6"),
    "key_6": ("Item1", "Item5", "Item6"),
    "key_7": ("Item3", "Item4", "Item7"),
    "key_8": ("Item1", "Item5", "Item8"),
    "key_9": ("Item3", "Item5", "Item8"),
}

Upvotes: 1

Related Questions