Home > database >  Issue using map function
Issue using map function

Time:03-22

I'm currently attempting to create a function that reads through a nested dictionary searching for a certain key, then returns the tuple if the first element is greater than the second - all without using recursion or loops. The output should look like this

input = { 
    1: { "A":(41,19), "B":(31,0),  "C":(59,24)}
    2: { "C":(10,20) }
    3: { "B":(1,2), "C":(4,3)}
}

function(input,'C')

output = [(1: (59,24)),(3:(4,3))]

Right now, if I run my code, my output is

[(1: (59,24))]

My code is as follows:

def wins_helper(dict,key,superkey):
    output_helper = []
    if dict[superkey][key][0] > dict[superkey][key][1]:
          output_helper.append(dict[superkey][key])
    output_helper.insert(0,superkey)
    return output_helper

def get_wins (input_dict,input_key):
    superkey_list = list(input_dict.keys())
    return list(map(wins_helper,[input_dict],[input_key],superkey_list))

I believe that I have used the map function incorrectly, but I'm not entirely sure what I need to do to fix it.

CodePudding user response:

This is the right way to solve this:

input = { 
    1: { "A":(41,19), "B":(31,0),  "C":(59,24)},
    2: { "C":(10,20) },
    3: { "B":(1,2), "C":(4,3)}
}

def function(dct, val):
    for k,v in dct.items():
        if val in v and v[val][0] > v[val][1]:
            yield (k,v[val] )

print(list(function(input,'C')))

Output:

[(1, (59, 24)), (3, (4, 3))]

Or, for those who like one-liners:

def function(dct, val):
    return [(k,v[val]) 
        for k,v in dct.items()
        if val in v and v[val][0] > v[val][1]]

print(function(input,'C'))

CodePudding user response:

You can just do this:

k = 'C'
output = [[n, d[k]] for n, d in input.items() if k in d and d[k][0] > d[k][1]]
# [[1, (59, 24)], [3, (4, 3)]]
  • Related