尽我所能学习一些Python。构建一个脚本,该脚本将获取一些参数并生成一个字典,以便稍后在脚本中使用。对此定义返回的对象有一些问题:
#!/usr/bin/python
from argparse import ArgumentParser
def argument_analysis():
"""
This will take in the arguments, and turn them into a filter dictionary
-n --name This will pinpoint a single host via hostname Tag
:return:filter_dictionary
"""
parser_options = ArgumentParser()
parser_options.add_argument("-n", "--name", dest='name', type=str, help="Filter by hostname.")
arguments = vars(parser_options.parse_args())
name_filter = arguments['name']
filter_dictionary = {}
if name_filter:
filter_dictionary = {"tag:Name", name_filter}
return filter_dictionary
elif len(filter_dictionary) < 1: return "No arguments."
if __name__ == '__main__':
args = argument_analysis()
print args
问题是当我运行它时(使用适用的选项):
$./test.py -n foo
set(['foo', 'tag:Name'])
但我期待这个输出:
{'tag:Name', 'foo'}
我似乎无法找到为什么我会得到一套&#39;返回而不是我创建的字典?我究竟做错了什么?在此先感谢您的帮助。
答案 0 :(得分:1)
{"tag:Name", name_filter}
表示集字面值。如果需要字典文字,则需要用冒号替换逗号:
filter_dictionary = {"tag:Name" : name_filter}
见下文:
>>> type({1, 'a'})
<class 'set'>
>>> type({1 : 'a'})
<class 'dict'>
>>>
以下是literals in Python的参考资料。
答案 1 :(得分:0)
您的语法不正确,而不是:
filter_dictionary = {"tag:Name", name_filter}
这是set
文字语法,你想要:
filter_dictionary = {"tag:Name": name_filter}
# ^ note colon, not comma
这是dict
文字语法。