简体   繁体   中英

Python-How to take a dictionary as input

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM