3

I want to assign an array (lists in a list) to a dictionary.

For this I have already tried the fromkeys() method. But this is not working as I've expected.

# a list with 3 string elements
list_of_Strings = ['index', 'substance', 'container']
# a list with 3 lists, each list has a few values
index_list = [0,1,2]
substance_list = ['water','oil','acetone']
container_list = ['B100','B200','B300']
list_of_lists = [index_list, substance_list, container_list]

# this line sets all for all dict keys the value to 0
dict_dummy_1 = dict.fromkeys(list_of_Strings,0)

# when I try this line, in every "key value" are all 3 lists from list_of_lists:
# Key -> Value
# index -> index_list, substance_list, container_list
# substance -> index_list, substance_list, container_list
# container -> index_list, substance_list, container_list
dict_dummy_1 = dict.fromkeys(list_of_Strings,list_of_lists)

# but I want to have it like this:
# Key -> Value
# index -> index_list
# substance -> substance_list
# container -> container_list

# with a loop it is possible:
dict_dummy_2 = dict.fromkeys(list_of_Strings,0)
for i in range(len(list_of_Strings)):
    dict_dummy_2[list_of_Strings[i]] = list_of_lists[i]

It is possible to avoid the loop solution? Is there any function for it? Thank you very much in advance. :)

DerDressing
  • 315
  • 1
  • 4
  • 19

3 Answers3

3

Here is a simple oneliner using zip:

dict(zip(list_of_Strings,list_of_lists))
yukashima huksay
  • 5,834
  • 7
  • 45
  • 78
1

You can use a dict-comprehension:

{list_of_Strings[i]: list_of_lists[i] for i in range(len(list_of_Strings))}
Carsten
  • 2,765
  • 1
  • 13
  • 28
0
# a list with 3 string elements
list_of_Strings = ['index', 'substance', 'container']
# a list with 3 lists, each list has a few values
index_list = [0,1,2]
substance_list = ['water','oil','acetone']
container_list = ['B100','B200','B300']
list_of_lists = [index_list, substance_list, container_list]


res = {i:j for i,j in zip(list_of_Strings, list_of_lists)}

print(res)

output

{'index': [0, 1, 2],
 'substance': ['water', 'oil', 'acetone'],
 'container': ['B100', 'B200', 'B300']}
sahasrara62
  • 10,069
  • 3
  • 29
  • 44