2

Is it possible to make this line of code valid?

description, content, state, city, datetime = makeTupleRightOrder(dictionary)

this makeTupleRightOrder would get the 'parameters' from the left side of the assignment, convert their names to strings and build a list getting their values from the dictionary.

6
  • rewrite it as map(lambda x:dictionary[x],[description, content, state, city, datetime]) Commented Apr 8, 2012 at 16:06
  • locals().update(dictionary) accomplishes your end goal of converting a dictionary to variable names. Commented Apr 8, 2012 at 16:27
  • 1
    @StevenRumbalski The contents of locals() should not be modified. Commented Apr 8, 2012 at 16:30
  • @JoshLee: Why not? That is what the OP is attempting with his code. Commented Apr 8, 2012 at 16:32
  • @Abhijit it's not working, python throws a name error (as suspected) Commented Apr 8, 2012 at 16:34

2 Answers 2

3

No. The function has no idea what's on the left side of the assignment, and even if it did, the variables might well have names different from the keys.

Sign up to request clarification or add additional context in comments.

Comments

2

kindall is right. For the general case, you can't do this. What you can do is sort the keys alphabetically, and always make sure that the variables you are unpacking the dict to are in the correct (alphabetic order) in terms of the keys:

city, content, datetime, description, state = [dictionary[k] for k in sorted(dictionary)]

(This example assumes the dictionary keys are named identically to the variables you are unpacking them to).

NOTE

If you are running into situations where you are forced to do this, I would consider designing your code differently. Your implementation is probably flawed.

2 Comments

This is definitely going too far, but if you made the variables on the left side into smart objects that 'knew' about eachother, you could have them exchange data until they had the right values. It would be cool, but utterly pointless.
@Joel: Even if the objects on the left side are somehow "smart", it doesn't matter because they will be totally different objects after the assignment. (It's not possible to override assignment in Python.)

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.