Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating dictionary with dynamic number of values as arguments

I'm running in a bit of trouble trying to get a script to work as a function.

The code below basically zips but for more than one list of values. So I can keep on adding list4, list5, etc.

list1 = ['USA', 'France', 'China']
list2 = [30, 39, 28]
list3 = [59.2, 93.1, 922.1]

dictionary = {}

for i in range(len(list1)):
    d[list1[i]] = list2[i], list3[i]

print(dictionary)

I'm looking for an output like:

{'USA': (30, 59.2), 'France': (39, 93.1), 'China': (28, 922.1)}

Now I want to turn that into a function, such as:

def zipMultiple(*values, keys):

    dictionary = {}

    for i in range(len(keys)):
        dictionary[keys[i]] = values[i]

    return dictionary

myDict = zipMultiple(list2, list3, keys=list1)

I get this error:

dictionary[keys[i]] = values[i] IndexError: tuple index out of range

I'm aware that it's probably due to assigning values[i] as though it was one list but I don't know how exactly to generalize it to say "create a tuple for every values (list) given as an argument.

like image 796
Faindirnomainzein Avatar asked Jan 27 '26 09:01

Faindirnomainzein


1 Answers

You need to perform a transpose operation so that the keys are appropriately aligned with the values:

def zipMultiple(*values, keys):
    dictionary = {}
    
    values = list(map(tuple, zip(*values)))
    for i in range(len(keys)):
        dictionary[keys[i]] = values[i]

    return dictionary

Or, you can make this a one-liner (with a suggested improvement by Joffan):

def zipMultiple(*values, keys):
    return dict(zip(keys, zip(*values)))

In both cases, the output is:

{'USA': (30, 59.2), 'France': (39, 93.1), 'China': (28, 922.1)}

Explanation:

If you print out the values inside the function (as initially passed in), you'll see:

([30, 39, 28], [59.2, 93.1, 922.1])

The first list contains the first element for each key, the second contains the second element for each key, etc.

But, this isn't what we're after. We want the first element to contain all the elements for the first key, the second elements to contain all the elements for the second key, etc.; we're after something like the following:

[
    (30, 59.2),
    (39, 93.1),
    (28, 922.1)
]

so that the keys are lined up in the same way as the values. To do this, we perform the transpose operation shown above.

like image 91
BrokenBenchmark Avatar answered Jan 28 '26 22:01

BrokenBenchmark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!