简体   繁体   中英

How to zip multiple lists into a nested dictionary in python

Having multiple lists and I would like to create a nested dictionary from them:

x = ['a','b','c','d']
keys_a = ['1','2','3','4']
values_a = [11,22,33,44]
keys_b = ['5','6','7','8']
values_b = [55,66,77,88]
keys_c = ['9','10','11','12']
values_c = [99,1010,1111,1212]
keys_d = ['13','14','15','16']
values_d = [1313,1414,1515,1616]

What I want to do is match a with keys_a and values_a, match b with keys_b and values_b, and c with keys_c and values_c, etc.

The expected output is the following:

d = {'a':{'1':11,
          '2':22,
          '3':33,
          '4':44},
     'b':{'5':55,
          '6':66,
          '7':77,
          '8':88},
     'c':{'9':99,
          '10':1010,
          '11':1111,
          '12':1212,
          '13':1313},
     'd':{'14':1414,
          '15':1515,
          '16':1616,
          '17':1717}}

Could you please help me to achieve this using python, I have tried with zip function but it doesn't give me the expected results. Is there any suggestions for the code I should write to have the expected output ?

Thank you !

If you're comfortable with list and dictionary comprehension, you can zip up x with a lists of your key lists and values lists. That looks like this:

output = {
    a: dict(zip(k, v))
    for a, k, v in zip(
        x,
        [keys_a, keys_b, keys_c, keys_d],
        [values_a, values_b, values_c, values_d]
)}

If that's a hard read (it is), you can use a more traditional for-loop like this:

output = {}
keys = [keys_a, keys_b, keys_c, keys_d]
values = [values_a, values_b, values_c, values_d]
for a, k, v in zip(x, keys, values):
    output[a] = dict(zip(k, v))

You can use the following code that uses the exec built-in function:

x = ['a', 'b', 'c', 'd']
keys_a = ['1', '2', '3', '4']
values_a = [11, 22, 33, 44]
keys_b = ['5', '6', '7', '8']
values_b = [55, 66, 77, 88]
keys_c = ['9', '10', '11', '12']
values_c = [99, 1010, 1111, 1212]
keys_d = ['13', '14', '15', '16']
values_d = [1313, 1414, 1515, 1616]

d = {}

for val in x:
    c = {}

    exec(f"""\
for key, val in zip(keys_{val}, values_{val}):
    c[key] = val
""")


    d[val] = c

print(d)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM