1

I have a txt file which I need to read start from PERSON_INFO which to extract name, age, hometown, gender of the person into dictionary:

information for one person PERSON_INFO:    **name**=paul   **age**=26  **hometown**=london **gender**=male
information for one person PERSON_INFO:    **name**=mei    **age**=27  **hometown**=taiwan **gender**=female
.
.
.

this is my code

import pandas as pd
result = []
with open("sample.txt", "r") as f:  # Replace this with `open(filename) as f:`

for line in f:
    line = line.strip().split()
    d = {}
    for l in line[1:]:
        k, v = l.rsplit("=")
        k = k.replace("*", "")
        d[k] = v
    result.append(d)

but it shows error:

k, v = l.rsplit("=") ValueError: not enough values to unpack (expected 2, got 1)

my expected output is

[{'name': 'paul', 'age': '26', 'hometown': 'london', 'gender': 'male'}, {'name': 'mei', 'age': '27', 'hometown': 'taiwan', 'gender': 'female'}]
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
  • 1
    What's the expected output? – Roy2012 Jul 13 '20 at 05:58
  • `rsplit` returns a list of one or more elements; assigning that list to two variables only works when the list has exactly two elements (i.e. the input token contains exactly one `=` character). – tripleee Jul 13 '20 at 06:00
  • @Roy2012 the expected output is [{'name': 'paul', 'age': '26', 'hometown': 'london', 'gender': 'male'}, {'name': 'mei', 'age': '27', 'hometown': 'taiwan', 'gender': 'female'}] –  Jul 13 '20 at 06:00
  • 1
    You have tried in correct way. Only correction is: `for l in line[5:]` variable line containing: `['information', 'for', 'one', 'person', 'PERSON_INFO:', '**name**=paul', '**age**=26', '**hometown**=lon don', '**gender**=male']` So you have to ignore 1st 5 elements. – Harsha Biyani Jul 13 '20 at 06:05
  • 1
    @HarshaBiyani got it! thank you so much! –  Jul 13 '20 at 06:09

1 Answers1

0

You might want to check and see what l is in that case, but I think it might be a single word. A word in your text might not contain an = sign. This will return an array with a single element. You're excepting two since you're storing the result in the variables k and v

S. Strempfer
  • 290
  • 2
  • 6