-1

I'm looking for a way to be able to define dictionary keys by function parameters. In the code below I make divisions of the first and second letters of the dictionary keys but Python's function parameters are not strings.

def x(a, b, c):
    dict = {'ab': 0, 'ac': 0, 'bc': 0}

    for d, e in dict.keys:
        dict[de] = d/e

x(10, 20, 30)
George R
  • 43
  • 1
  • 1
  • 5
  • 3
    Uhm, what? Please give a complete example of what you are trying to achieve, with input and output. I don't understand your question at all. That function name x is not very descriptive either. – timgeb Feb 09 '16 at 14:22
  • Why not just pass a dictionary to `x`? – SuperBiasedMan Feb 09 '16 at 14:26
  • 1
    You can't divide letters by letters. What do you expect the result to be? – Sven Marnach Feb 09 '16 at 14:27
  • It would help if you gave some sample input and expected output. – PM 2Ring Feb 09 '16 at 14:28
  • I think this is a "dynamic variables" question in disguise. He wants `dict["ab"]` to be set to `a/b` rather than `"a"/"b"`. For example, `x(300, 6, 2) == {"ab": 50, "ac": 150, "bc": 3}` – Kevin Feb 09 '16 at 14:30
  • @Kevin Yes that is correct – George R Feb 09 '16 at 14:38
  • Variable variables are almost always a bad idea, but try experimenting with the [`locals`](https://docs.python.org/3/library/functions.html#locals) function. – Kevin Feb 09 '16 at 14:42
  • Would it be ok if the function took keyword args, so you could call it like `ratios(a=600, b=3, c=2)`? With the returned dictionary being `{'ac': 300.0, 'ab': 200.0, 'bc': 1.5}` – PM 2Ring Feb 09 '16 at 14:45
  • 1
    Do have a look at [How do I do variable variables in Python?](http://stackoverflow.com/q/1373164) – Bhargav Rao Feb 09 '16 at 14:53

1 Answers1

0

Here's some code that will handle any number of arguments. It first sorts the argument names into alphabetical order. Then it creates all pairs of arguments and performs the divisions (with the value of the earlier arg in alphabetical order being divided by the value of the later one), storing the results in a dict, with the dict's keys being constructed by the concatenating the argument names. The function returns the constructed dict, but of course in your code you may wish to perform further actions on it.

from itertools import combinations

def ratios(**kwargs):
    pairs = combinations(sorted(kwargs.keys()), 2)
    return dict((p + q, kwargs[p] / kwargs[q]) for p, q in pairs)

print(ratios(a=600, b=3, c=2))    

output

{'ac': 300.0, 'ab': 200.0, 'bc': 1.5}
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182