Home > Back-end >  Slicing a List Converting a Nested List into a Dictionary
Slicing a List Converting a Nested List into a Dictionary

Time:06-30

I have a list of items, which has a name and item description in the same string. I was able to slice them and separate into item names and item description, however when items do not have description, how can I create an empty description for its item name?

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

for item in lst:
    new_lst.append(str(item).split('-', 1))

print(new_lst)

My output looks like this

[['Macbook Air ', ' 13inch Model'], ['Iphone13 ', ' Max Pro 65GB Model'], ['Airpod2']]

but I want them looks like this

[['Macbook Air ', ' 13inch Model'], ['Iphone13 ', ' Max Pro 65GB Model'], ['Airpod2','']]

eventually my goals is to convert a nested list into a dictionary. So I would like to use item names as keys and descriptions as its values like below

[{'Macbook Air ':' 13inch Model'}, {'Iphone13 ':' Max Pro 65GB Model'}, {'Airpod2':''}]

CodePudding user response:

This is a great usecase for the string.partition method:

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

for item in lst:
    product, _, desc = str(item).partition('-')
    new_lst.append([product, desc])

print(new_lst)
# [['Macbook Air ', ' 13inch Model'], ['Iphone13 ', ' Max Pro 65GB Model'], ['Airpod2', '']]

string.partition is behaviorally the exact same as string.split(..., 1) except that string.partition is always guaranteed to return a tuple of 3 items (empty strings if no successful split could be performed).


If you want a dictionary output, you can do the same but just store your results directly into a dictionary:

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

out = {}
for item in lst:
    product, _, desc = item.partition('-')
    out[product] = desc
 
print(out)
# {'Macbook Air ': ' 13inch Model', 'Iphone13 ': ' Max Pro 65GB Model', 'Airpod2': ''}

CodePudding user response:

Maybe this what you're looking for? Try this out and ask question, if any.

Note - the output is One dictionary with all items.

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': []})

CodePudding user response:

Technically, what you've shown in the last code block is a list of dictionaries. I'm assuming you want a dictionary that holds all devices as keys and descriptions as values. Please let me know if that's not what you're trying to do.

I would do a check on the format: Does the provided element have the format 'Device - Description'? You can use a regex or use the way you've chosen. For the latter, you would need to check if str(item).split('-') returns a list with two elements, and if not, find a way to create an empty description.

Having done that, you can add the device and description to your dictionary by doing new_lst[item] = description. Problem so far: Your new_lst is no dictionary, but a list. So either initialize it by calling dict() or declare it like this: new_lst = {}

  • Related