David Abraham David Abraham - 20 days ago 6
Python Question

Locating the dictionary within a list when inputting a specific value

let us say we have a few clusters represented as dictionaries below:

cluster1 = {'Disks' : [0,1,2,3,12] , 'left': True , 'right': False}
cluster2 = {'Disks' : [3,4,5,2] , 'left':True ,'right': False }
cluster3 = {'Disks' : [6,7,8,2] , 'left':False ,'right': False }
cluster4 = {'Disks' : [10,11,12] , 'left':True, 'right':True }

Listofclusters = [cluster1,cluster2,cluster3,cluster4]


Then I make a list of the clusters as above to store them....

If i want to search the list for a particular disk and would like it to tell me which clusters within the list have those disks
how would i do that?

Answer

According to your requirement:

to search the list for a particular disk and would like it to tell me which clusters within the list have those disks

Use the following approach which will form a dict cluster_numbers which key is a disk number and value is a list of cluster names(cluster order numbers)
Let's find all cluster names(numbers) which have one or more disk numbers from the following list [2, 10, 7]

search_disks = [2, 10, 7]
cluster_numbers = {d:[] for d in search_disks}

for d in cluster_numbers.keys():
    for k, c in enumerate(Listofclusters):
        if d in c['Disks']: cluster_numbers[d].extend(['cluster' + str(k+1)])

print(cluster_numbers)

The output:

{2: ['cluster1', 'cluster2', 'cluster3'], 10: ['cluster4'], 7: ['cluster3']}
Comments