-2

I am trying to combine a set of lists into an organized dictionary. The existing lists are in the following format:

index = [1, 2]
keys = [key1, key2, key3]
values_k1 = [a, b, c]
values_k2 = [d, e, f]

I want to organize those lists into the following dictionary:

d = {'1': {'key1':'a','key2':'b','key3':'c'}, '2': {'key1':'d','key2':'e','key3','f'}}
martineau
  • 119,623
  • 25
  • 170
  • 301
afc6
  • 11
  • 1

2 Answers2

3

Look up dictionary comprehensions and the zip api.

d = {
    i: dict(zip(keys, values)) 
    for i, values in zip(index, [values_k1, values_k2])
}

If the index is always incremental you can remove the index array and do something like this:

all_values = [values_k1, values_k2]
d = {
    i: dict(zip(keys, values)) 
    for i, values in enumerate(all_values)
}

And if d always has keys that are incremental you might as well use a list which can be accessed by index value anyways:

all_values = [values_k1, values_k2]
d = [dict(zip(keys, values)) for values in all_values]
flakes
  • 21,558
  • 8
  • 41
  • 88
0

I don't know you should, but you can make a nested dictionary comprehension.

{i:{k:v for k,v in zip(keys,vals)} for i,vals in zip(index,(values_k1, values_k2))}
fsimonjetz
  • 5,644
  • 3
  • 5
  • 21