Sehal Hasan
Sehal Hasan

Reputation: 23

How to get elements from a nested list in python based on key, value pairs?

['ISBN: 9789353765170', 'Pages: 64', 'Size: 294 x 219', 'Language: English', 'Book Binding: Paperback', 'Weight: 350 gm.']

I splitted with l.split(":"), to get a nested list but that isn't helping

[['ISBN', ' 9789353765170'], ['Pages', ' 64'], ['Size', ' 294 x 219'], ['Language', ' English'], ['Book Binding', ' Paperback'], ['Weight', ' 350 gm.']]

I have a list that looks like the above, I want to append these attribute values into separate lists of their own so that I can create a dataframe using them. The problem is that some lists also have the "format" attribute as well in the list. How do I specifically choose these elements to be added into their own lists and for the non existent attributes to be added "Not available" in python.

Upvotes: 1

Views: 120

Answers (1)

jezrael
jezrael

Reputation: 863246

IIUC use:

L = ['ISBN: 9789353765170', 'Pages: 64', 'Size: 294 x 219',
     'Language: English', 'Book Binding: Paperback', 'Weight: 350 gm.']


df = pd.DataFrame((x.split(': ') for x in L), columns=['a','b'])
print (df)
              a               b
0          ISBN   9789353765170
1         Pages              64
2          Size       294 x 219
3      Language         English
4  Book Binding       Paperback
5        Weight         350 gm.

Upvotes: 1

Related Questions