mercredi 3 novembre 2021

Iterate over lists as values in dictionary to search for specific values, then add the key of that value to new lists, in Python

I have a dictionary consisting of several keys with values that are lists, as such:

Dict = {keyA:[1, 3, 2], keyB:[2, 3, 4], keyC:[1,4,3]}

I want to create lists from this values, named from the values. The items in these lists are the keys that had these values in their corresponding lists.

list1 = [keyA, keyC]
list2 = [keyA, keyB]
list3 = [keyA, keyB, keyC]

So far I have managed to name the lists after the values that are existing in the dictionary value-lists:

Max_No = 12
N = 0
while N < Max_No: 
    N = N + 1
    locals()["list"+str(N)] = []

But when I try to expand this with while loops, so that I can iterate through the dictionary keys and values, things break down:

Max_No = 12
N = 0
while N < Max_No: 
    N = N + 1
    locals()["list"+str(N)] = []


N = 0
for key, value in Dict:
    while N < Max_No:
        N = N + 1
        if N in value:
            locals()["list"+str(N)].append(key)

Any help would be greatly appreciated!

The error message i get is:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

Aucun commentaire:

Enregistrer un commentaire