-1

I'm not sure if this is possible, but is there a way to combine 3 lists into a dictionary so that the list name is the key and the list of items is the value?

Example:

Inputs:

list1 = ['a', 'b', 'c'] 
list2 = ['d', 'e', 'f']
list3 = ['g', 'h', 'i']

output:

dict = {
  'list1': ['a', 'b', 'c'],
  'list2': ['d', 'e', 'f'],
  'list3': ['g', 'h', 'i']
}

thanks

bergerg
  • 985
  • 9
  • 23
slim s
  • 107
  • 7

2 Answers2

3

if you're able to define your list in its own function,
(so they are the only variables in the local function),
you can do this:

def loc():    
  list1 = ['a', 'b', 'c']
  list2 = ['d', 'e', 'f']
  list3 = ['g', 'h', 'i']

  list_dictionary = (locals())

  print(list_dictionary)

loc()

{'list1': ['a', 'b', 'c'], 'list2': ['d', 'e', 'f'], 'list3': ['g', 'h', 'i']}


Otherwise, you may need to resort to something more like this:

list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']    
list3 = ['g', 'h', 'i']

list_dictionary = {}
for i in ('list1', 'list2', 'list3'):
  list_dictionary[i] = locals()[i]

print (list_dictionary)

{'list1': ['a', 'b', 'c'], 'list2': ['d', 'e', 'f'], 'list3': ['g', 'h', 'i']}

source: https://stackoverflow.com/a/3972978/5411817


if your variable names are repetitive, as in the example, you can compose a list of strings for the variable names:

variable_names_as_strings = []
for i in range(1,4):
    variable_names_as_strings.append('list' + str(i))

Then create your dictionary:

for i in variable_names_as_strings:
  list_dictionary[i] = locals()[i]
print (list_dictionary)

{'list1': ['a', 'b', 'c'], 'list2': ['d', 'e', 'f'], 'list3': ['g', 'h', 'i']}


more info on locals() (also look up globals()):
https://www.programiz.com/python-programming/methods/built-in/locals https://docs.python.org/3.3/library/functions.html#locals
SherylHohman
  • 16,580
  • 17
  • 88
  • 94
0
list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
list3 = ['g', 'h', 'i']

dictionary = dict()

dictionary['list1'] = list1
dictionary['list2'] = list2
dictionary['list3'] = list3

print(dictionary)

output:

{'list1': ['a', 'b', 'c'], 'list2': ['d', 'e', 'f'], 'list3': ['g', 'h', 'i']}