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.

Markus Unterwaditzer
  • 7,992
  • 32
  • 60
hakuna121
  • 243
  • 5
  • 10
  • 18
  • You could try the solution posted here: http://stackoverflow.com/questions/988228/converting-a-string-to-dictionary – pkacprzak Jun 23 '13 at 19:02
  • Your "What I tried" part gives me a dict in the python 2.7 interpreter! – Atmaram Shetye Jun 23 '13 at 19:02
  • @zaphod: You're using Python 2, the OP is using Python 3. Try ``raw_input`` as an equivalent. – Markus Unterwaditzer Jun 23 '13 at 19:03
  • @zaphod sorry about the confusion! – hakuna121 Jun 23 '13 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? – Sylvain Leroux Jun 23 '13 at 19:07
  • @SylvainLeroux your reading make more sense. Thank you! – hakuna121 Jun 23 '13 at 19:20

1 Answers1

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!

enpenax
  • 1,476
  • 1
  • 15
  • 27