Home > Enterprise >  Slicing a List Converting a Nested List into a Dictionary ( Pairing a List of Values to the key)
Slicing a List Converting a Nested List into a Dictionary ( Pairing a List of Values to the key)

Time:07-03

I previously asked a question here, about how to slice strings and using them as keys and values, and people helped me to come up with a solution which is below:

from collections import defaultdict

lst = [
    'Macbook Air - 13inch Model',
    'Iphone13 - Max Pro 65GB Model',
    'Airpod2'
    ]
dc = defaultdict(str)

for item in lst:
    x, *y = item.split('-')
    dc[x] = y
    
print(dc)

Output:

defaultdict(<class 'str'>, {'Macbook Air ': [' 13inch Model'], 'Iphone13 ': [' Max Pro 65GB Model'], 'Airpod2': []})

however, what if it ends up generating the same key and I wanted to have a list of values paired within the same key name?

for example:

lst = [
    'Macbook Air - 13inch Model',
    'Iphone13 - Max Pro 65GB Model',
    'Iphone13 - Max 128GB Model',
    'Airpod2'
    ]

and output will be looking like:

defaultdict(<class 'str'>, {'Macbook Air ': [' 13inch Model'], 'Iphone13 ': [' Max Pro 65GB Model', 'Pro 128GB Model'], 'Airpod2': []})

I assumed it will automatically stored more than one values but it only paired with the first key and value and others with the same key name disappeared.

CodePudding user response:

Make it a defaultdict of lists rather than strings:

from collections import defaultdict

lst = [
    'Macbook Air - 13inch Model',
    'Iphone13 - Max Pro 65GB Model',
    'Iphone13 - Max 128GB Model',
    'Airpod2'
    ]
dc = defaultdict(list)

for item in lst:
    x, *y = item.split('-')
    dc[x].extend(y)

gives you a dc with the following contents:

defaultdict(<class 'list'>, {
    'Macbook Air ': [' 13inch Model'],
    'Iphone13 ': [' Max Pro 65GB Model', ' Max 128GB Model'],
    'Airpod2': []
})
  • Related