DragonToes DragonToes - 3 years ago 129
Python Question

How do you return key-value pairs from a function where the key is the input and the value is the output?

I am looping a function over a list of values

inputs
that returns a list of values
outputs
like this:

outputs = []
for i in inputs[:]:
outputs.append(str(function(i)))


How do I set up a dictionary that populates key value pairs of inputs and outputs like below?

input1, output1
input2, output2

Answer Source

You can just map your function over the input, then zip the result with the original input and pass that sequence of tuples to dict:

d = dict(zip(inputs, [str(function(i)) for i in inputs]))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download