0

I'm trying to make a dictionary with a set number of keys and the values as lists of strings from an already zipped object, like so:

{'FirstKey': ['1234', '5678', '9123'], 'SecondKey': ['null', 'null', 'null']...}

Each string in every values list comes from a different variable, and if I have three variables, I can get the desired result if I manually zip them:

valuesList = zip(finalValue[0], finalValue[1], finalValue[2])

Dictionary = dict(zip(keysList, valuesList))

This works for three variables, but the problem is that the list of variables can differ, and I'm not sure how to make a loop for whatever number. I've tried appending the variables into a list and making a dictionary with the keys and that list, but then the variables become strings and I get:

{'FirstKey': ('finalValue[0]',), 'SecondKey': ('finalValue[1]',)...}

I get an "arg must be a string, bytes or code object" error when I use eval() on the list of variables, so I'm not quite sure what to do. Any help would be appreciated.

iqaris
  • 3
  • 1
  • 1
    It doesn't sound like you actually want to zip two lists of varying size, like your question title implies. It sounds like you want to zip *a varying number of* lists. Yes? – Karl Knechtel Aug 07 '21 at 16:03
  • 1
    We really need to see an example of your inputs – JonSG Aug 07 '21 at 16:05
  • 2
    Does https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters answer your question? – Karl Knechtel Aug 07 '21 at 16:05

1 Answers1

1

You may use the star * operator to unpack the list of values without knowing how many there is

finalValue = [
    [1, 2, 3],
    ['a', 'b', 'c'],
    ['d', 'e', 'f']
]

keysList = ['ka', 'kb', 'kc']

valuesList = zip(*finalValue)
result = dict(zip(keysList, valuesList))

print(result)  # {'ka': (1, 'a', 'd'), 'kb': (2, 'b', 'e'), 'kc': (3, 'c', 'f')}
azro
  • 53,056
  • 7
  • 34
  • 70