1

Specs: Python3.3.2

What I intend to do:

Take a dictionary as input and return one as output, but the values are now the keys and vice versa

Question: I believe that I can figure out the key-and-value-switch part. But I don't know how to take a dictionary as input.(and keep the object type as dict)

What I tried:

a = input("Please enter a dictionary: ")
print(a)

Result: {'a':1,'b':2}. BUT:

This turned out to be a string object, as is shown using type(a) and getting <class 'str'> as result.

6
  • You could try the solution posted here: stackoverflow.com/questions/988228/… Commented Jun 23, 2013 at 19:02
  • Your "What I tried" part gives me a dict in the python 2.7 interpreter! Commented Jun 23, 2013 at 19:02
  • @zaphod: You're using Python 2, the OP is using Python 3. Try raw_input as an equivalent. Commented Jun 23, 2013 at 19:03
  • @zaphod sorry about the confusion! Commented Jun 23, 2013 at 19:06
  • 4
    ... well ... I'm not certain the OP as clearly understood the terms of his assignment? "Take a dictionary as input and return one as output" -- Should "input" be interpreted literally as "from the input() function"? Or, as I am inclined to think, should we understand "write a function receiving a dictionary as argument and returning an other one such as ..." Or am I just too tired to read things correctly? Commented Jun 23, 2013 at 19:07

1 Answer 1

3

Everything you input in a terminal, will always be a string! Hence, if you enter a correct dict you have to transform it first by executing the given string like this:

import ast
a = input("Please enter a dictionary: ")
d = ast.literal_eval(a)
print d

However, looking at the comments to your question. I don't think somebody would ask you to parse a dict like that from the commandline. Hence, the task probably wants you to just write up a function to receive a dict and print it out, or probably play with it so you can see the difference between mutables and immutables in python and how they are passed around!

Cheers!

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

3 Comments

@user2246674 It is seen around here very often. It's way better and safer than using eval().
Another option would be to use json.loads.
Thanks! I think your reading of the question make more sense than mine. Parsing is a little too complicated for a beginner as I am right now.

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.