0

I'm working through a book on Python3 and linear algebra. I'm trying to take a string with the format 'name junk junk 1 1 1 1 1' and make a dictionary with the name in the and the numbers converted from strings to ints. i.e. {name:[1,1,1,1,1]} But I can't quite figure out the loop, as I'm a python newbie. Here's my code:

string = 'Name junk junk -1 -1 1 1'
for i, x in string.split(" "):
        if i == 0:
            a = x
        if i > 2:
            b = int(x)

Running that code nets the following error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

Ideally I'd also like it to be a comprehension. But I can probably figure that part out if I can get the loop.

2
  • In Python, assignments are statements (only), not expressions. I'm not sure what you are trying to do with a and b, but it could be difficult to turn it into a single comprehension, since the first element of a comprehension is an expression. Commented Mar 27, 2015 at 18:42
  • What about that "junk junk"? Just junk? Commented Mar 27, 2015 at 18:49

1 Answer 1

5

Did you mean to use enumerate?

for i, x in enumerate(string.split(" ")):
     # ...

Using a list comprehension:

tokens = string.split() # Splits by whitespace by default, can drop " "
result = {tokens[0]: [int(x) for x in tokens[3:]]} # {'Name': [-1, -1, 1, 1]}
Sign up to request clarification or add additional context in comments.

1 Comment

I never thought about doing it that way. Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.