Home > Software engineering >  Iterate through python dictionary and appending key component in two lists
Iterate through python dictionary and appending key component in two lists

Time:12-05

I have the following dictionary, tempDict

{('M1', 'P1'): 6.0,
 ('M1', 'P2'): 10.0,
 ('M1', 'P3'): 4.0,
 ('M2', 'P1'): 7.0,
 ('M2', 'P2'): 9.0,
 ('M2', 'P3'): 5.0}

I am doing some operations over this dictionary and taking the some key components to a list. Say I have l1 = [], l2 = [].

Suppose minimum value is 4 the I find that jobsR as ('M1', 'P3').I would like to remove the all the keys where 'P3' appears from the tempDict.

I will be finding the minimum value from this dictionary iteratively and will drop corresponding keys. As the keys are ordered pairs, if the departed key element has 1st component M1 then I shall take the 2nd component in list l1 else in l2. I shall continue until the dictionary becomes empty. My code is,

while bool(tempDict):
    try:
        l1 = []
        l2 = []
        valMin = min(tempDict.values())
        jobsR = [key for key in tempDict if tempDict[key] == valMin]
        for (x, y) in jobsR:
            if x == 'M1':
                l1.append(y)
            else:
                l2.append(y)
        remove_list = []
        for key, value in tempDict.items():
            if jobsR[0][1] in key[1]:
                remove_list.append(key)
        for item in remove_list:
            tempDict.pop(item)
    except KeyError:
        print('The dictionary has no item now...')
        break

Expected output:

l1 = [P3, P1] and l2 = [P2]

Code_Updated

l1 = []
l2 = []
while bool(tempDict):
    valMin = min(tempDict.values())
    jobsR = [key for key in tempDict if tempDict[key] == valMin]
    remove_list = []
    for key, value in tempDict.items():
        if jobsR[0][1] in key[1]:
            remove_list.append(key)
    for item in remove_list:
        tempDict.pop(item)
    for x in jobsR:
        #print(x[0])
        if x[0] == 'M1':
            l1.append(item[1])
        else:
            l2.append(item[1])

CodePudding user response:

lists l1 and l2 are set into [ ] in every cycle of the while loop. Declare l1 and l2 outside of the while loop to get the expected output.

CodePudding user response:

You need to take l1 and l2 out of the while loop and pop keys as you go:

l1 = []
l2 = []
while tempDict:
    min_val = min(tempDict.values())
    jobsR = [k for k,v in tempDict.items() if v==min_val][0]
    if jobsR[0] == 'M1':
        l1.append(jobsR[1])
    else:
        l2.append(jobsR[1])
    for k in tempDict:
        if k[1]==jobsR[1]]:
            tempDict.pop(k)

Output:

# l1 = ['P3', 'P1']
# l2 = ['P2']

Note: This assumes each minimum value has a unique key.

  • Related