Search code examples
pythondictionaryfor-loopzip

How to store values of multiple lists in nested dicts?


I've looked at the documentation of how to convert two lists into a dictionary but it doesn't seem to apply here. So a simple zip function won't do the trick here. I've tried a lot of different things which all lead to messy headache code lines. I've outlined the result I'm looking for below.

list_01 = ['name_01', 'name_02', 'name_03']
list_02 = ['size_01', 'size_02', 'size_03']
list_03 = ['path_01', 'path_02', 'path_03']
list_04 = ['count_01', 'count_02', 'count_03']

data = {}

Result I'm looking for:

{'data': {'name_01': {
                    'name':'name_01',
                    'size':'size_01',
                    'path':'path_01',
                    'count':'count_01'},
        'name_02': {
                    'name':'name_02',
                    'size':'size_02',
                    'path':'path_02',
                    'count':'count_02'}
        'name_03': {
                    'name':'name_03',
                    'size':'size_03',
                    'path':'path_03',
                    'count':'count_03'}}}

A side question would be why I often see list brackets in dicts when working json? A list in this example wouldn't make sense for me (source: link) Is it a good choice to use lists instead of dicts in dicts?

{
    "people": [
        {
            "from": "Nebraska",
            "name": "Scott",
            "website": "stackabuse.com"
        }
    ]
}

Solution

  • data['data'] = {name:{'name': name, 'size': size, 'path': path, 'count': count} 
        for name, size, path, count in zip(list_01, list_02, list_03, list_04)}
    

    result of pprint.pprint(data)

    {'data': {'name_01': {'count': 'count_01',
                          'name': 'name_01',
                          'path': 'path_01',
                          'size': 'size_01'},
              'name_02': {'count': 'count_02',
                          'name': 'name_02',
                          'path': 'path_02',
                          'size': 'size_02'},
              'name_03': {'count': 'count_03',
                          'name': 'name_03',
                          'path': 'path_03',
                          'size': 'size_03'}}}