Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python定义返回";“设置”;什么时候应该还字典?_Python_Dictionary_Set - Fatal编程技术网

Python定义返回";“设置”;什么时候应该还字典?

Python定义返回";“设置”;什么时候应该还字典?,python,dictionary,set,Python,Dictionary,Set,只是尽力学点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

只是尽力学点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
但我期待这一结果:

{'tag:Name', 'foo'}

我似乎找不到为什么返回的是“set”而不是我创建的字典?我做错了什么?提前感谢您的帮助。

您的语法不正确,而不是:

filter_dictionary = {"tag:Name", name_filter}
这是
set
literal语法,您需要:

filter_dictionary = {"tag:Name": name_filter}
                             # ^ note colon, not comma
这是
dict
文字语法。

{“tag:Name”,Name\u filter}
表示一组文字。如果需要字典文字,则需要将逗号替换为冒号:

filter_dictionary = {"tag:Name" : name_filter}
见下文:

>>> type({1, 'a'})
<class 'set'>
>>> type({1 : 'a'})
<class 'dict'>
>>>
>类型({1,'a'})
>>>类型({1:'a'})
>>>

这是关于的参考资料。

OMG非常感谢您。整个上午我都在用头敲击键盘。我很惭愧我错过了。谢谢你抽出时间。天哪,非常感谢。整个上午我都在用头敲击键盘。我很惭愧我错过了。谢谢你抽出时间。
>>> type({1, 'a'})
<class 'set'>
>>> type({1 : 'a'})
<class 'dict'>
>>>