[英]Python-How to take a dictionary as input
Specs: Python3.3.2 规格: 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
) 但我不知道如何把字典作为输入。(并保持对象类型为
dict
)
What I tried: 我尝试了什么:
a = input("Please enter a dictionary: ")
print(a)
Result: {'a':1,'b':2}
. 结果:
{'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. 这被证明是一个字符串对象,如使用
type(a)
和得到<class 'str'>
作为结果所示。
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:
因此,如果输入正确的dict,则必须首先执行给定的字符串,如下所示:
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. 我不认为有人会要求你从命令行解析这样的
dict
。 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! 因此,任务可能希望你只是编写一个函数来接收一个dict并将其打印出来,或者可能与它一起玩,这样你就可以看到python中的mutable和immutables之间的区别以及它们是如何传递的!
Cheers! 干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.